引入maven依赖
引入powermock是为了解决静态方法mock的问题。
1<dependency> 2 <groupId>org.powermock</groupId> 3 <artifactId>powermock-module-junit4</artifactId> 4 <version>2.0.2</version> 5 <scope>test</scope> 6</dependency> 7<dependency> 8 <groupId>org.powermock</groupId> 9 <artifactId>powermock-api-mockito2</artifactId> 10 <version>2.0.2</version> 11 <scope>test</scope> 12</dependency> 13<dependency> 14 <groupId>org.mockito</groupId> 15 <artifactId>mockito-core</artifactId> 16 <version>2.28.2</version> 17 <scope>test</scope> 18</dependency> 19<dependency> 20 <groupId>org.assertj</groupId> 21 <artifactId>assertj-core</artifactId> 22 <version>3.11.1</version> 23 <scope>test</scope> 24</dependency> 25<dependency> 26 <groupId>org.mockito</groupId> 27 <artifactId>mockito-all</artifactId> 28 <version>2.0.2-beta</version> 29 <scope>test</scope> 30</dependency>
构建单元测试目录
标准的maven单元测试目录一样,在resources目录里面添加application.yml内容如下:
1spring: 2 profiles: 3 active: test 4 5--- 6spring: 7 profiles: test 8 9dc: 10 security: 11 auditlog: 12 module: "System Manage" #模块名 13logging: 14 level: 15 root: INFO
定义Application入口类
1@ActiveProfiles("test") 2@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class, MultipartAutoConfiguration.class}) 3public class Application4Test extends SpringBootServletInitializer { 4 5 @Override 6 protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { 7 return application.sources(Application4Test.class); 8 } 9 10 public static void main(String[] args) { 11 SpringApplication.run(Application4Test.class, args); 12 } 13}
抽象测试父类
1@RunWith(PowerMockRunner.class) 2@PowerMockRunnerDelegate(SpringRunner.class) 3@PowerMockIgnore({"javax.management.*","javax.net.*", "javax.net.ssl.*"}) 4@SpringBootTest(classes = Application4Test.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) 5@ActiveProfiles("test") 6@ContextConfiguration(initializers = {ApplicationInitializer4Test.class}) 7public abstract class AbstractSpringTest { 8 9 @MockBean 10 protected ISecurityContextService securityContextService; 11 @Autowired 12 protected Map<String, HttpRequestInterceptor> HttpRequestInterceptorMap; 13 @SpyBean 14 protected HttpClientProperties httpClientProperties; 15 @Autowired 16 @Qualifier("restTemplate") 17 protected RestTemplate eurekaRestTemplate; 18 @Autowired 19 @Qualifier("simpleRestTemplate") 20 protected RestTemplate simpleRestTemplate; 21}
启动覆盖yml配置
如果yml文件中的配置项需要覆盖,可实现ApplicationContextInitializer
1public class ApplicationInitializer4Test implements ApplicationContextInitializer<ConfigurableApplicationContext> { 2 3 private static final Logger logger = LoggerFactory.getLogger(ApplicationInitializer4Test.class); 4 5 @Override 6 public void initialize(ConfigurableApplicationContext applicationContext) { 7 Resource rootCertResource = new ClassPathResource("cert/root.p12"); 8 Resource serverCertResource = new ClassPathResource("cert/server.p12"); 9 String rootCertPath = ""; 10 String clientCertPath = ""; 11 try { 12 File rootCertFile = rootCertResource.getFile(); 13 File serverCertFile = serverCertResource.getFile(); 14 rootCertPath = rootCertFile.getCanonicalPath().replaceAll("\\\\", "/"); 15 clientCertPath = serverCertFile.getCanonicalPath().replaceAll("\\\\", "/"); 16 logger.info("rootCertFilePath=" + rootCertPath); 17 logger.info("clientCertFilePath=" + clientCertPath); 18 } catch (IOException e) { 19 e.printStackTrace(); 20 } 21 TestPropertySourceUtils.addInlinedPropertiesToEnvironment( 22 applicationContext, "server.ssl.keyStore=" + clientCertPath); 23 TestPropertySourceUtils.addInlinedPropertiesToEnvironment( 24 applicationContext, "server.ssl.trustStore=" + rootCertPath); 25 } 26}
实际单元测试用例
1@PrepareForTest({SecurityContextHolder.class, ClientContextHolder.class}) 2public class ApiOperationLogServiceTest extends AbstractSpringTest { 3 4 private ApiOperationLogService operationLogService; 5 6 @Before 7 public void setUp() throws Exception { 8 System.out.println("###################test start##########################"); 9 operationLogService = new ApiOperationLogService(properties, restTemplate); 10 } 11 12 @After 13 public void tearDown() throws Exception { 14 System.out.println("###################test end##########################"); 15 } 16 17 @Test 18 public void save() { 19 ResultVo resultVo = new ResultVo(); 20 resultVo.setResultCode(0); 21 resultVo.setResultMessage("save log success"); 22 ResponseEntity<ResultVo> response = new ResponseEntity<>(resultVo, HttpStatus.OK); 23 doReturn(response).when(restTemplate).exchange(eq(properties.getOperationLogUrl()), eq(HttpMethod.POST), 24 isA(HttpEntity.class), eq(ResultVo.class)); 25 operationLogService.save(new OperationLog()); 26 } 27 28 @Test 29 public void testLoadOperatorId() { 30 // PowerMockito打桩,模拟静态方法 31 PowerMockito.mockStatic(SecurityContextHolder.class); 32 SecurityContextImpl securityContext = new SecurityContextImpl(); 33 securityContext.setAuthentication( 34 new UsernamePasswordAuthenticationToken("xiongneng", "123456")); 35 PowerMockito.when(SecurityContextHolder.getContext()).thenReturn(securityContext); 36 assertEquals(operationLogService.loadOperatorId(), "xiongneng"); 37 } 38 39 @Test 40 public void testLoadClientIpWhenRemoteUserIp() { 41 // PowerMockito打桩,模拟静态方法 42 PowerMockito.mockStatic(ClientContextHolder.class); 43 ClientContext clientContext = new ClientContext(); 44 clientContext.setClientIP("192.168.20.22"); 45 clientContext.setRemoteUserIP("30.200.12.22"); 46 PowerMockito.when(ClientContextHolder.getContext()).thenReturn(clientContext); 47 assertEquals(operationLogService.loadClientIp(), "30.200.12.22"); 48 } 49 50 @Test 51 public void testLoadClientIpWhenNoRemoteUserIp() { 52 // PowerMockito打桩,模拟静态方法 53 PowerMockito.mockStatic(ClientContextHolder.class); 54 ClientContext clientContext = new ClientContext(); 55 clientContext.setClientIP("192.168.20.22"); 56 PowerMockito.when(ClientContextHolder.getContext()).thenReturn(clientContext); 57 assertEquals(operationLogService.loadClientIp(), "192.168.20.22"); 58 } 59}
调用Controller接口测试
1public class RestTemplateTest extends AbstractSpringTest { 2 3 @LocalServerPort 4 private int port; 5 6 private URL base; 7 8 @Before 9 public void setUp() throws Exception { 10 this.base = new URL("https://localhost:" + port); 11 } 12 13 @Test 14 public void testBidirectionCertificate() { 15 ResponseEntity<String> response = simpleRestTemplate.getForEntity(base.toString() + "/welcome", String.class); 16 assertEquals(response.getBody(), "welcome"); 17 } 18}
MockBean和SpyBean区别
spy对象和mock对象的两点区别:
1、默认行为的不同
对于未指定mock的方法,spy默认会调用真实的方法,有返回值的返回真实的返回值,而mock默认不执行,有返回值的,默认返回null
2、mock的使用方式不同
mock对象的使用方式,spy对象这样使用会直接调用该方法,所以无法这样使用,比如:
Mockito.when(obj.domethod(parm1, param2)).thenReturn(result);
spy对象的使用方式,要先执行do等方法,mock对象也可以这样使用,比如:
Mockito.doReturn(info).when(obj).domethod(param1, param2);
@Spy 和 @SpyBean 的区别,@Mock 和 @MockBean的区别
- spy和mock生成的对象不受spring管理
- spy调用真实方法时,其它bean是无法注入的,要使用注入,要使用SpyBean
- SpyBean和MockBean生成的对象受spring管理,相当于自动替换对应类型bean的注入,比如@Autowired等注入
模拟void方法
对void方法的模拟有两种方式,一种是通过抛出异常,一种是通过Answer来指定void的执行过程。
抛出期望的异常:
doThrow(RuntimeException.class).when(daoMock).updateEmail(any(Customer.class), any(String.class));
指定void的执行过程:
1doAnswer((Answer<Void>) invocation -> { 2 Object[] args = invocation.getArguments(); 3 System.out.println("restTemplate.exchange called with arguments: " + Arrays.toString(args)); 4 return null; 5}).when(restTemplate).exchange(anyString(), eq(HttpMethod.POST), 6 isA(HttpEntity.class), eq(ResultVo.class)); 7 8// 执行真实方法 9doAnswer(Answers.CALLS_REAL_METHODS.get()).when(mock).voidMethod(any(SomeParamClass.class));