– Start
假设我们有如下类。
package demo04;
import java.util.ArrayList;
import java.util.List;
public class BusinessService {
private List<String> users = new ArrayList<>();
public void addUser(String user) {
users.add(user);
}
}
下面我们看看访问私有字段。
package demo04;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.reflect.Whitebox;
@RunWith(PowerMockRunner.class)
@PrepareForTest({ BusinessService.class })
public class BusinessServiceTest {
@Test
public void test() throws Exception {
String testUser = "test";
BusinessService businessService = new BusinessService();
businessService.addUser(testUser);
// 访问私有域
List<String> users = Whitebox.getInternalState(businessService, "users");
// 验证
Assert.assertTrue(users.contains(testUser));
}
}
– 更多参见:PowerMock 精萃
– 声 明:转载请注明出处
– Last Updated on 2019-08-17
– Written by ShangBo on 2019-08-17
– End