Mockito
2020年4月12日 星期日
下午10:10
Mockito
Mockito Quick Start
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.10.19</version>
<scope>test</scope>
</dependency>
How to mockito?
- @Runwith(MockitoJunitRunner.class)
- @Rule
- Public MockitoRule mockito = MockitoJunit.rule();
- MockitoAnnotations.initMocks(this);
- Deep mock
Demo
packagecom.yangshaojun.springboot.app;
importcom.yangshaojun.springboot.app.controller.MockController;
importcom.yangshaojun.springboot.app.entity.User;
importcom.yangshaojun.springboot.app.service.MockService;
importorg.junit.Assert;
importorg.junit.Test;
importorg.junit.runner.RunWith;
importorg.mockito.InjectMocks;
importorg.mockito.Mock;
importorg.mockito.Mockito;
importorg.springframework.boot.test.context.SpringBootTest;
importorg.springframework.test.context.junit4.SpringRunner;
/**
*@ClassName:MockControllerTest
*@Description:
*@Author:yangshaojun
*@Date:2020-04-12
*@Version:v1.0
*/
@RunWith(SpringRunner.class)
@SpringBootTest
publicclassMockControllerTest{
@Mock
MockServicemockService;
@InjectMocks
MockControllermockController=newMockController();
@Test
publicvoidtestQueryUserSuccess(){
Useruser=newUser();
user.setId(1);
Mockito.when(mockService.queryUser(Mockito.any())).thenReturn(user);
StringqueryUser=mockController.queryUser();
System.out.println(queryUser);
Assert.assertEquals("success",queryUser);
}
@Test
publicvoidtestQueryUserFail(){
Useruser=newUser();
user.setId(1);
Mockito.when(mockService.queryUser(Mockito.any())).thenThrow(RuntimeException.class);
StringqueryUser=mockController.queryUser();
System.out.println(queryUser);
Assert.assertEquals("fail",queryUser);
}
@Test
publicvoidtestQueryUserNull(){
Useruser=newUser();
user.setId(1);
Mockito.when(mockService.queryUser(Mockito.any())).thenReturn(null);
StringqueryUser=mockController.queryUser();
System.out.println(queryUser);
Assert.assertEquals("null",queryUser);
}
}