单元测试开发
1 常用注解
1.1 @ExtendWith(MockitoExtension.class)
使@Mock、@Spy、@InjectMocks等注解生效
1.2 @InjectMocks使用
https://www.jianshu.com/p/bb705a56f620
注意:In Mockito 2 there is a MockitoAnnotations.initMock() method, which is deprecated and replaced with MockitoAnnotations.openMocks() in Mockito 3. The MockitoAnnotations.openMocks() method returns an instance of AutoClosable which can be used to close the resource after the test.
junit5中使用@InjectMocks注解,不需要再调用 MockitoAnnotations.openMocks()使其他被@mock、@spy注解的对象注入生效
https://www.arhohuttunen.com/junit-5-mockito/
2 如何注入需要的非public字段数据
https://www.jianshu.com/p/1b04c698c56b
ReflectionTestUtils.setField(myController, "myService", myService);
3 mock new对象(采用Mockito.mockConstruction方法)
try (MockedConstruction<Dog> mock = mockConstruction(Dog.class, (mock, context) -> {
// 这里的mock相当于new出来的mock对象
Mockito.when(mock.methodWithParam(Mockito.anyString(), Mockito.anyInt())).thenReturn(1); // mock有参的方法
Mockito.doNothing().when(mock).voidMethod(); // mock无参的方法
})) {
// creating a mock instance
Dog dog = new Dog();
when(dog.makeSound()).thenReturn("Bark");
assertThat(dog.makeSound()).isEqualTo("Bark");
// Get a list of all created mocks
List<Dog> constructed = mock.constructed();
assertThat(constructed).hasSize(1);
}
4 mock 静态对象
1、注解形式:
@Mock
MockedStatic<StaticObject> staticObject;

浙公网安备 33010602011771号