1、在项目中配置Mockito
Maven:
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.9.0</version>
<scope>test</scope>
dependency
2、创建Mock
两种方法:
第一种,通过静态方法mock()
Flower flowerMock=Mockito.mock(Flower.class);
第二种,通过@Mock 注释
@Mock
备注:要想使用注释@Mock的方式,必须通过下面两种方式:
- MockitoAnnotations.initMocks( testClass ), 在setUp()方法中调用MockitoAnnotations.initMocks(this);
- @RunWith(MockitoJUnit4Runner)
3、 模拟调用某个方法返回给定的值。
when(Mock的内容).thenReturn(返回值)
when(outXXXDao.selectXXXByCode("bjjd")).thenReturn(result);
备注:
- @mock为一个interface提供一个虚拟的实现。
- @InjectMocks将被测试类中的mock(或@mock)注入到被标注的对象中去,也就是说被标注的对象中需要使用标注了mock(或@mock)的对象。
另外Mockito对特殊的行为还提供了很多其他方法。
METHOD | DESCRIPTION |
thenReturn(T valueToBeReturned) | Returns given value |
thenThrow(Throwable toBeThrown) thenThrow(Class<? extends Throwable> toBeThrown) |
Throws given exception |
then(Answer answer) thenAnswer(Answer answer) |
Uses user-created code to answer |
thenCallRealMethod() | Calls real method when working with partial mock/spy |
例如:
when(mock.someMethod(
"some arg"
)) .thenThrow(
new
RuntimeException()) .thenReturn(
"foo"
);
- mock()/@Mock: create mock
-
- optionally specify how it should behave via Answer/ReturnValues/MockSettings
- when()/given() to specify how a mock should behave
- If the provided answers don’t fit your needs, write one yourself extending the Answerinterface
- spy()/@Spy: partial mocking, real methods are invoked but still can be verified and stubbed
- @InjectMocks: automatically inject mocks/spies fields annotated with @Spy or @Mock
- verify(): to check methods were called with given arguments
- Try Behavior-Driven development syntax with BDDMockito