SpringBoot2单元测试

Stella981
• 阅读 934

引入maven依赖

引入powermock是为了解决静态方法mock的问题。

<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内容如下:

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文件中的配置项需要覆盖,可实现ApplicationContextInitializer

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对象的两点区别:

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的区别

  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));
点赞
收藏
评论区
推荐文章
blmius blmius
3年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
待兔 待兔
5个月前
手写Java HashMap源码
HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22
Jacquelyn38 Jacquelyn38
3年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
Easter79 Easter79
3年前
SpringBoot2单元测试
引入maven依赖引入powermock是为了解决静态方法mock的问题。<dependency<groupIdorg.powermock</groupId<artifactIdpowermockmodulejunit4</artifactId<versi
Wesley13 Wesley13
3年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Wesley13 Wesley13
3年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
3年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Wesley13 Wesley13
3年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
11个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这