转载:https://blog.csdn.net/apexlj/article/details/50298029
mockito可模拟依赖对象的行为,从而简化跨类的测试。
maven获取mockito:
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.10.19</version>
</dependency>
以下例:
- 被测类:ConnInfoService
- 依赖类:ConnInfoAccessor
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "/conf/test-context.xml")
public class ConnInfoServiceTest {
@Autowired
@InjectMocks
private ConnInfoService connInfoService;
@Mock
private ConnInfoAccessor connInfoAccessor;
@Before
public void before() throws Exception {
MockitoAnnotations.initMocks(this);
}
/**
* Method: getConnInfo(String connId)
*/
@Test
public void testGetConnInfo() throws Exception {
GPSConnInfo gpsConnInfo = new GPSConnInfo();
gpsConnInfo.setAppKey("appKey");
gpsConnInfo.setGpsNodeId("node1");
when(connInfoAccessor.getConnInfo("connId")).thenReturn(gpsConnInfo);
Assert.assertEquals(gpsConnInfo, connInfoService.getConnInfo("connId"));
}
/**
* Method: saveConnInfo(String connId, GPSConnInfo gpsConnInfo)
*/
@Test(expected = GPSServiceException.class)
public void testSaveConnInfo() throws Exception {
GPSConnInfo gpsConnInfo = new GPSConnInfo();
gpsConnInfo.setAppKey("appKey");
gpsConnInfo.setGpsNodeId("node1");
doThrow(new DataAccessException("e") {
@Override
public String getMessage() {
return super.getMessage();
}
}).when(connInfoAccessor).saveConnInfo("connId", gpsConnInfo);
connInfoService.saveConnInfo("connId", gpsConnInfo);
}
- @InjectMocks用于标识被测对象,从而把由@mock表示的依赖对象自动注入到被测对象中
- @Mock用于表示依赖对象
- MockitoAnnotations.initMocks(this);用于初始化以上注入动作
when(connInfoAccessor.getConnInfo("connId")).thenReturn(gpsConnInfo)
用于模拟带返回值的getConnInfo方法的处理doThrow(new DataAccessException("e") {
用于模拟无返回值的saveConnInfo方法抛出异常的行为
@Override
public String getMessage() {
return super.getMessage();
}
}).when(connInfoAccessor).saveConnInfo("connId", gpsConnInfo);