参考:http://site.mockito.org/mockito/docs/current/org/mockito/junit/MockitoRule.html
如果想使用@Mock, @Spy, @InjectMocks等注解时,需要进行初始化后才能使用。
初始化的方法有3种:
1,在Junit的类上面使用@RunWith(MockitoJUnitRunner.class)注解。
但如果你使用的是Spring的话,可能你会使用Spring的测试类(@RunWith(SpringJUnit4ClassRunner.class))
这样的话,你就没有办法使用上面的@RunWith(SpringJUnit4ClassRunner.class)。你还可以使用下面的方法。
2,在测试方法被调用之前,使用MockitoAnnotations.initMocks(this);。例如:
@Before
public void initMocks(){
MockitoAnnotations.initMocks(this);
}
@Before保证了在被测试的方法被调用之前,调用@Before所注解的方法
这个方法还有下面的好处。(具体是什么样子还没有试过)
Allows shorthand creation of objects required for testing.
Minimizes repetitive mock creation code.
Makes the test class more readable.
Makes the verification error easier to read because field name is used to identify the mock.
3,使用MockitoRule。如下:
@Rule
public MockitoRule rule = MockitoJUnit.rule();
这个方法会调用validateMockitoUsage方法。这个方法有一些好处,具体什么好处还不太清楚。