每次写单元测试都要重复写一些方法、注解等,这里我写了一下测试的基类
基类
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());
}
}