spring-boot單元測試對weblistener的載入測試
阿新 • • 發佈:2019-02-10
使用spring-boot對web專案進行測試時對weblistener進行載入.以proxool連線池的載入為例.
//原監聽器程式碼
//spring-boot測試適配修改,繼承TestExcutionListener介面,實現prepareTestInstance方法,將監聽業務同樣放在此方法中做預處理即可.@WebListener public class ProxoolListener implements ServletContextListener{ @Override public void contextDestroyed(ServletContextEvent arg0) { } @Override public void contextInitialized(ServletContextEvent arg0) { loadProxool(); } ...//其他實現方法 }
@WebListener public class ProxoolListener implements ServletContextListener,TestExecutionListener{ @Override public void contextDestroyed(ServletContextEvent arg0) { } @Override public void contextInitialized(ServletContextEvent arg0) { loadProxool(); } @Override public void afterTestClass(TestContext arg0) throws Exception { // TODO 自動生成的方法存根 } @Override public void afterTestMethod(TestContext arg0) throws Exception { // TODO 自動生成的方法存根 } @Override public void beforeTestClass(TestContext arg0) throws Exception { // TODO 自動生成的方法存根 } @Override public void beforeTestMethod(TestContext arg0) throws Exception { // TODO 自動生成的方法存根 } @Override public void prepareTestInstance(TestContext arg0) throws Exception { //啟動測試時需要預先的處理 loadProxool(); } }
//測試類
@RunWith(SpringJUnit4ClassRunner.class) @TestExecutionListeners(listeners = { ProxoolListener.class , DependencyInjectionTestExecutionListener.class }) public class DemoApplicationTest { @Test public void exampleTest() { try { System.out.println("Connection is closed : "+ProxoolUtility.getConnection("proxool.iovdc").isClosed()); } catch (SQLException e) { e.printStackTrace(); } } }