注意,在你输入@RunWith注解时,Eclipse会自动导入org.powermock.modules.junit4.legacy.PowerMockRunner包,记得把它换成org.powermock.modules.junit4.PowerMockRunner,否则会抛java.lang.NoClassDefFoundError.
public boolean callArgumentInstance(File file) {
return file.exists();
}
测试用例代码:
@Test
public void testCallArgumentInstance() {
File file = PowerMockito.mock(File.class);
ClassUnderTest underTest = new ClassUnderTest();
PowerMockito.when(file.exists()).thenReturn(true);
Assert.assertTrue(underTest.callArgumentInstance(file));
}
说明:普通Mock不需要加@RunWith和@PrepareForTest注解。
public String getFilePath() {
return path;
}
public String getPayloadName() {
String pathWithName = getFilePath();
try {
int index = pathWithName.lastIndexOf(Constant.SLASH);
return pathWithName.substring(index + 1);
}
catch (Exception e) {
return pathWithName;
}
}
测试用例代码:
@Test
public void testGetPayloadName() throws Exception {
FileItem item = PowerMockito.mock(FileItem.class);
String filePath = "../../../test/updates/Citrix.ibr";
PowerMockito.when(item.getFilePath()).thenReturn(filePath);
PowerMockito.when(item, "getPayloadName").thenCallRealMethod();
assertEquals("Citrix.ibr", item.getPayloadName());
}
说明:当使用mock出来的对象去调用某个方法时,要对该方法使用thenCallRealMethod().
public class ClassUnderTest {
public boolean callInternalInstance(String path) {
File file = new File(path);
return file.exists();
}
}
测试用例代码:
@RunWith(PowerMockRunner.class)
@PrepareForTest(ClassUnderTest.class)
public class TestClassUnderTest {
@Test
public void testCallInternalInstance() throws Exception {
File file = PowerMockito.mock(File.class);
ClassUnderTest underTest = new ClassUnderTest();
PowerMockito.whenNew(File.class).withArguments("bing").thenReturn(file);
PowerMockito.when(file.exists()).thenReturn(true);
Assert.assertTrue(underTest.callInternalInstance("bing"));
}
}
说明:当使用PowerMockito.whenNew方法时,必须加@PrepareForTest和@RunWith注解。注解@PrepareForTest里写的类是需要mock的new对象代码所在的类。
public class ClassUnderTest{
public boolean callFinalMethod(Dependency d){
return d.isAlive();
}
}
class Dependency{
public final boolean isAlive(){
// do something
return true;
}
}
测试用例代码:
@RunWith(PowerMockRunner.class)
public class TestClassUnderTest {
@Test
@PrepareForTest(Dependency.class)
public void testCallFinalMethod() {
Dependency depencency = PowerMockito.mock(Dependency.class);
ClassUnderTest underTest = new ClassUnderTest();
PowerMockito.when(depencency.isAlive()).thenReturn(true);
Assert.assertTrue(underTest.callFinalMethod(depencency));
}
}
说明: 当需要mock final方法的时候,必须加@PrepareForTest和@RunWith注解,@PrepareForTest里写的类是final方法所在的类。
public class ClassUnderTest{
public boolean callPrivateMethod(){
return isAlive();
}
private boolean isAlive(){
// do something
return true;
}
}
测试用例代码:
@RunWith(PowerMockRunner.class)
@PrepareForTest(ClassUnderTest.class)
public class TestClassUnderTest {
@Test
public void testCallFinalMethod() {
ClassUnderTest underTest = new ClassUnderTest();
PowerMockito.when(underTest.callPrivateMethod().thenCallRealMethod();
PowerMockito.when(underTest, "isAlive").thenReturn(true);
Assert.assertTrue(underTest.callPrivateMethod());
}
}
说明: 和mock final方法一样,必须加@PrepareForTest和@RunWith注解,@PrepareForTest里写的类是private方法所在的类。
public class ClassUnderTest{
public boolean callStaticMethod(Dependency d){
return Dependency.isExist();
}
}
class Dependency{
public static boolean isExist(){
// do something
return true;
}
}
测试用例代码:
@RunWith(PowerMockRunner.class)
public class TestClassUnderTest {
@Test
@PrepareForTest(Dependency.class)
public void testCallFinalMethod() {
PowerMockito.mockStatic(Dependency.class);
ClassUnderTest underTest = new ClassUnderTest();
PowerMockito.when(Dependency.isExist()).thenReturn(true);
Assert.assertTrue(underTest.callStaticMethod(depencency));
}
}
说明: mock静态方法时需要加@PrepareForTest和@RunWith注解,@PrepareForTest注解中是静态方法所在的类。
public class RefreshMgmt{
private static final String MSG_DOWNLOAD_FAILED = Messages.getString("RefreshThread.0");
public boolean downloadFiles(String path) {
return download(path);
}
private boolean download(String localPath){
// do something
return false;
}
}
测试用例代码:
@RunWith(PowerMockRunner.class)
@PrepareForTest({ RefreshMgmt.class, Messages.class })
public class TestRefreshMgmt {
@Test
public void testDownloadFiles() throws Exception {
PowerMockito.suppress(PowerMockito.method(Messages.class, "getString", String.class));
//PowerMockito.suppress(PowerMockito.field(RefreshMgmt.class, "MSG_DOWNLOAD_FAILED");
RefreshMgmt mgmt = PowerMockito.mock(RefreshMgmt.class);
PowerMockito.when(mgmt, "download", Matchers.anyString()).thenReturn(true);
PowerMockito.when(mgmt.downloadFiles(Matchers.anyString())).thenCallRealMethod();
assertTrue(mgmt.downloadFiles("C:/temp"));
}
}
说明: PowerMockito.suppress方法原来禁用某个域或方法,在本例中初始化Messages类会抛出空指针异常,因public class CataElement{
private boolean isAvailable = false;
private List items = new ArrayList<>();
private Date parseDate(String date) {
if(!isAvailable)
return null;
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
try {
if (date == null || date.isEmpty())
return null;
return sdf.parse(date);
}
catch (ParseException e) {
Log.log(Log.WARN, e, getClass());
return null;
}
}
}
测试用例代码:
public class CataElementTest{
@Test
public void test(){
CataElement e = new CataElement();
Whitebox.setInternalState(e, "isAvailable", true);
// other things
List items = Whitebox.getInternalState(e, "items");
assertTrue(items.size == 0);
}
}
@Test
public void test() {
final EmployeeService mock = PowerMockito.mock(EmployeeService.class);
final Employee employee = new Employee();
PowerMockito.when(mock.findEmployeeByEmail(Matchers.anyString())).then(new Answer() {
public Employee answer(InvocationOnMock invocation) throws Throwable {
final String email = (String) invocation.getArguments()[0];
if(email == null) return null;
if(email.startsWith("deep")) return employee;
if(email.endsWith("packtpub.com")) return employee;
return null;
}
});
final EmployeeController employeeController = new EmployeeController(mock);
assertSame(employee, employeeController.findEmployeeByEmail("[email protected]"));
assertSame(employee, employeeController.findEmployeeByEmail("[email protected]"));
assertNull(employeeController.findEmployeeByEmail("[email protected]"));
}
说明:改测试方法根据不同的参数返回不同的结果,Answer的泛型类型必须和answer方法的返回值类型一致。