每次寫單元測試都要重複寫一些方法、註解等,這裏我寫了一下測試的基類
基類
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());
}
}