引入powermock是爲了解決靜態方法mock的問題。java
<dependency> <groupId>org.powermock</groupId> <artifactId>powermock-module-junit4</artifactId> <version>2.0.2</version> <scope>test</scope> </dependency> <dependency> <groupId>org.powermock</groupId> <artifactId>powermock-api-mockito2</artifactId> <version>2.0.2</version> <scope>test</scope> </dependency> <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-core</artifactId> <version>2.28.2</version> <scope>test</scope> </dependency> <dependency> <groupId>org.assertj</groupId> <artifactId>assertj-core</artifactId> <version>3.11.1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-all</artifactId> <version>2.0.2-beta</version> <scope>test</scope> </dependency>
標準的maven單元測試目錄同樣,在resources目錄裏面添加application.yml內容以下:web
spring: profiles: active: test --- spring: profiles: test dc: security: auditlog: module: "System Manage" #模塊名 logging: level: root: INFO
@ActiveProfiles("test") @SpringBootApplication(exclude = {DataSourceAutoConfiguration.class, MultipartAutoConfiguration.class}) public class Application4Test extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(Application4Test.class); } public static void main(String[] args) { SpringApplication.run(Application4Test.class, args); } }
@RunWith(PowerMockRunner.class) @PowerMockRunnerDelegate(SpringRunner.class) @PowerMockIgnore({"javax.management.*","javax.net.*", "javax.net.ssl.*"}) @SpringBootTest(classes = Application4Test.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @ActiveProfiles("test") @ContextConfiguration(initializers = {ApplicationInitializer4Test.class}) public abstract class AbstractSpringTest { @MockBean protected ISecurityContextService securityContextService; @Autowired protected Map<String, HttpRequestInterceptor> HttpRequestInterceptorMap; @SpyBean protected HttpClientProperties httpClientProperties; @Autowired @Qualifier("restTemplate") protected RestTemplate eurekaRestTemplate; @Autowired @Qualifier("simpleRestTemplate") protected RestTemplate simpleRestTemplate; }
若是yml文件中的配置項須要覆蓋,可實現ApplicationContextInitializerspring
public class ApplicationInitializer4Test implements ApplicationContextInitializer<ConfigurableApplicationContext> { private static final Logger logger = LoggerFactory.getLogger(ApplicationInitializer4Test.class); @Override public void initialize(ConfigurableApplicationContext applicationContext) { Resource rootCertResource = new ClassPathResource("cert/root.p12"); Resource serverCertResource = new ClassPathResource("cert/server.p12"); String rootCertPath = ""; String clientCertPath = ""; try { File rootCertFile = rootCertResource.getFile(); File serverCertFile = serverCertResource.getFile(); rootCertPath = rootCertFile.getCanonicalPath().replaceAll("\\\\", "/"); clientCertPath = serverCertFile.getCanonicalPath().replaceAll("\\\\", "/"); logger.info("rootCertFilePath=" + rootCertPath); logger.info("clientCertFilePath=" + clientCertPath); } catch (IOException e) { e.printStackTrace(); } TestPropertySourceUtils.addInlinedPropertiesToEnvironment( applicationContext, "server.ssl.keyStore=" + clientCertPath); TestPropertySourceUtils.addInlinedPropertiesToEnvironment( applicationContext, "server.ssl.trustStore=" + rootCertPath); } }
@PrepareForTest({SecurityContextHolder.class, ClientContextHolder.class}) public class ApiOperationLogServiceTest extends AbstractSpringTest { private ApiOperationLogService operationLogService; @Before public void setUp() throws Exception { System.out.println("###################test start##########################"); operationLogService = new ApiOperationLogService(properties, restTemplate); } @After public void tearDown() throws Exception { System.out.println("###################test end##########################"); } @Test public void save() { ResultVo resultVo = new ResultVo(); resultVo.setResultCode(0); resultVo.setResultMessage("save log success"); ResponseEntity<ResultVo> response = new ResponseEntity<>(resultVo, HttpStatus.OK); doReturn(response).when(restTemplate).exchange(eq(properties.getOperationLogUrl()), eq(HttpMethod.POST), isA(HttpEntity.class), eq(ResultVo.class)); operationLogService.save(new OperationLog()); } @Test public void testLoadOperatorId() { // PowerMockito打樁,模擬靜態方法 PowerMockito.mockStatic(SecurityContextHolder.class); SecurityContextImpl securityContext = new SecurityContextImpl(); securityContext.setAuthentication( new UsernamePasswordAuthenticationToken("xiongneng", "123456")); PowerMockito.when(SecurityContextHolder.getContext()).thenReturn(securityContext); assertEquals(operationLogService.loadOperatorId(), "xiongneng"); } @Test public void testLoadClientIpWhenRemoteUserIp() { // PowerMockito打樁,模擬靜態方法 PowerMockito.mockStatic(ClientContextHolder.class); ClientContext clientContext = new ClientContext(); clientContext.setClientIP("192.168.20.22"); clientContext.setRemoteUserIP("30.200.12.22"); PowerMockito.when(ClientContextHolder.getContext()).thenReturn(clientContext); assertEquals(operationLogService.loadClientIp(), "30.200.12.22"); } @Test public void testLoadClientIpWhenNoRemoteUserIp() { // PowerMockito打樁,模擬靜態方法 PowerMockito.mockStatic(ClientContextHolder.class); ClientContext clientContext = new ClientContext(); clientContext.setClientIP("192.168.20.22"); PowerMockito.when(ClientContextHolder.getContext()).thenReturn(clientContext); assertEquals(operationLogService.loadClientIp(), "192.168.20.22"); } }
public class RestTemplateTest extends AbstractSpringTest { @LocalServerPort private int port; private URL base; @Before public void setUp() throws Exception { this.base = new URL("https://localhost:" + port); } @Test public void testBidirectionCertificate() { ResponseEntity<String> response = simpleRestTemplate.getForEntity(base.toString() + "/welcome", String.class); assertEquals(response.getBody(), "welcome"); } }
spy對象和mock對象的兩點區別:api
一、默認行爲的不一樣app
對於未指定mock的方法,spy默認會調用真實的方法,有返回值的返回真實的返回值,而mock默認不執行,有返回值的,默認返回nulldom
二、mock的使用方式不一樣maven
mock對象的使用方式,spy對象這樣使用會直接調用該方法,因此沒法這樣使用,好比:ide
Mockito.when(obj.domethod(parm1, param2)).thenReturn(result);
spy對象的使用方式,要先執行do等方法,mock對象也能夠這樣使用,好比:單元測試
Mockito.doReturn(info).when(obj).domethod(param1, param2);
@Spy
和 @SpyBean
的區別,@Mock
和 @MockBean
的區別測試
對void方法的模擬有兩種方式,一種是經過拋出異常,一種是經過Answer來指定void的執行過程。
拋出指望的異常:
doThrow(RuntimeException.class).when(daoMock).updateEmail(any(Customer.class), any(String.class));
指定void的執行過程:
doAnswer((Answer<Void>) invocation -> { Object[] args = invocation.getArguments(); System.out.println("restTemplate.exchange called with arguments: " + Arrays.toString(args)); return null; }).when(restTemplate).exchange(anyString(), eq(HttpMethod.POST), isA(HttpEntity.class), eq(ResultVo.class)); // 執行真實方法 doAnswer(Answers.CALLS_REAL_METHODS.get()).when(mock).voidMethod(any(SomeParamClass.class));