使用如下方式在Maven中添加EasyMock的依赖:
<dependency>
<groupId>org.easymockgroupId>
<artifactId>easymockartifactId>
<version>3.4version>
<scope>testscope>
dependency>
先“录制”后使用:
- 先创建一个mock对象: EasyMock.createMock
- 录制对象的行为(打桩)
- 声明录制完成:EasyMock.replay
UserDao mock = EasyMock.createMock(UserDao.class);//创建Mock对象
EasyMock.expect(mock.getById("1001")).andReturn(expectedUser);//录制Mock对象预期行为
EasyMock.expect(mock.getById("1002")).andThrow(new RuntimeException());
EasyMock.replay(mock);//重放Mock对象,测试时以录制的对象预期行为代替真实对象的行为
EasyMock.expect(mock.getById("1001")).andThrow(new RuntimeException());
EasyMock.expect(mock.getById(EasyMock.isA(String.class))).andReturn(exceptedUser).times(3);
isA()方法会使用instanceof进行参数类型匹配,类似的方法还有anyInt(),anyObject(),
isNull(),same(), startsWith()……
mock.updateUserById(“TestId”);
EasyMock.expectLastCall().anytimes();
//EasyMock.expectLastCall().andThrow(new RuntimeException()).anytimes();
EasyMock.expect(rs.next()).andReturn(true).times(2).andReturn(false).times(1);
<properties>
<powermock.version>1.6.6powermock.version>
properties>
<dependencies>
<dependency>
<groupId>org.powermockgroupId>
<artifactId>powermock-api-easymockartifactId>
<version>${powermock.version}version>
<scope>testscope>
dependency>
<dependency>
<groupId>org.powermockgroupId>
<artifactId>powermock-module-junit4artifactId>
<version>${powermock.version}version>
<scope>testscope>
dependency>
dependencies>
先“声明”,再“录制”,后使用
- 声明powermock:当前测试类增加注解 @RunWith(PowerMockRunner.class)
- 声明需要操作字节码的类 @PrepareForTest({clzz1.class, clzz2.class})
- 录制对象的行为(打桩)
- 声明录制完成:PowerMock.replayAll
@RunWith(PowerMockRunner.class)
public class SystemPropertyMockDemoTest {
@Test
public void demoOfFinalSystemClassMocking() throws Exception {
PowerMock.mockStatic(System.class);
PowerMock.when(System.getProperty("property")).thenReturn("my property");
PowerMock.replayAll();
//enjoy your mock
}
}
对于JDK的类如果要进行静态或final方法Mock时,不需要放在@PrepareForTest里面
@PrepareForTest({……})
注解既可以加在类层次上(对整个测试文件有效),也可以加在测试方法上(只对测试方法有效)。
@RunWith(PowerMockRunner.class)
@PrepareForTest(DataService.class)
public class DataServiceTest {
@Test
public void testReplaceData() throws Exception {
DataService tested = PowerMock.createPartialMock(DataService.class, "modifyData");//创建部分mock对象,只对modifyData方法Mock
PowerMock.expectPrivate(tested, "modifyData", "id", null).andReturn(true);//录制私有方法
PowerMock.replay(tested);
assertTrue(tested.deleteData(“id”));
PowerMock.verify(tested);
}
}
File fileMock = PowerMock.createMockAndExpectNew(File.class, "directoryPath");
参考:使用PowerMock和Easymock进行单元测试
参考:github: powermock