1. 程式人生 > >Spring Web 項目Junit測試報錯問題

Spring Web 項目Junit測試報錯問題

繼承 text config web項目 cap 正是 obj ssr and

測試對象是Web項目的Service類,參照網上查到的資料,按如下方式執行時報錯,

//使用junit4進行單元測試
@RunWith(SpringJUnit4ClassRunner.class)
//加載配置文件,可以指定多個配置文件,locations指定的是一個數組
@ContextConfiguration(locations={"classpath:spring/applicationContext-*.xml", "classpath:spring/springmvc.xml"})
//啟動事務控制
@Transactional
//配置事務管理器,同時指定自動回滾
@TransactionConfiguration(transactionManager="transactionManager", defaultRollback=true)
public class BaseJunit4Test {
    //進行測試時,將測試類繼承該類
    //註入service對象
    //然後在方法上使用@Test,@RollBack,@Transaction等註解單獨修飾
}

執行後報錯如下:

  Caused by java.lang.IllegalStateException:WebApplicationObjectSupport instance[ResourceHttpRequestHandler [locations=[class path resource [assert/]],resolvers=[org.springframework.web.servlet.resource.PathResourceResolver@...]]] does not run in a WebApplicationContext but in : org.springframework.context.support.GenericAppliactionContext............

網上找到了類似的問題,說是在配置文件中將assert相關的靜態資源目錄去掉就可以了。感覺不靠譜,因為工程在tomcat中啟動是沒有什麽問題的。

剛開始用Junit,不太熟悉,後來想,可能是Junit配置沒有支持Web工程。然後又搜索怎麽對Controller層進行單元測試的,結果發現了測試類上面的@WebAppConfiguration註解。猜想正是因為少了這個註解的問題。

於是在測試代碼中加上了這個註解,就不報錯了。

Junit很強大,還是要好好學習一下的。

遇到問題,在此Mark一下。這是我的錯題集。

Spring Web 項目Junit測試報錯問題