SpringBoot2單元測試

引入maven依賴

引入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

定義Application入口類

@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配置

若是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");
    }
}

調用Controller接口測試

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");
    }
}

MockBean和SpyBean區別

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的區別測試

  1. spy和mock生成的對象不受spring管理
  2. spy調用真實方法時,其它bean是沒法注入的,要使用注入,要使用SpyBean
  3. SpyBean和MockBean生成的對象受spring管理,至關於自動替換對應類型bean的注入,好比@Autowired等注入

模擬void方法

對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));
相關文章
相關標籤/搜索