SpringBoot 测试基类

每次写单元测试都要重复写一些方法、注解等,这里我写了一下测试的基类

文章目录


在这里插入图片描述

基类

BaseApplicationTests.java测试基类,其他测试类继承此类即可。

package com.leigq.www.shiro.base;

import org.junit.After;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public abstract class BaseApplicationTests {

    protected Logger log = LoggerFactory.getLogger(this.getClass());

    private Long time;

    @Before
    public void setUp() {
        this.time = System.currentTimeMillis();
        log.info("==> 测试开始执行 <==");
    }

    @After
    public void tearDown() {
        log.info("==> 测试执行完成,耗时:{} ms <==", System.currentTimeMillis() - this.time);
    }
}

测试

ShiroApplicationTests.java 基类使用测试

package com.leigq.www.shiro.test;

import com.leigq.www.shiro.base.BaseApplicationTests;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;

public class ShiroApplicationTests extends BaseApplicationTests {

    @Autowired
    private DataSourceProperties dataSourceProperties;

    @Test
    public void contextLoads() {
        // 测试时候可以正确获取 DataSourceProperties bean
        log.warn("DriverClassName is {}", dataSourceProperties.getDriverClassName());
    }

}

在这里插入图片描述


作者:不敲代码的攻城狮
出处:https://www.cnblogs.com/leigq/
任何傻瓜都能写出计算机可以理解的代码。好的程序员能写出人能读懂的代码。

 
原文地址:https://www.cnblogs.com/leigq/p/13406547.html