使用springmvc 做開發時,需要對controller做測試,而有時候界面的設計比後臺功能性的開發速度還要慢,又想測試controller 的正確性時,就可以用上這種方法。
下面是一個 junit case
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"file:src/main/webapp/WEB-INF/applicationContext.xml","file:src/main/webapp/WEB-INF/dispatcherServlet-servlet.xml","file:src/main/webapp/WEB-INF/datasource/datasource.xml"}) //使用註解加載spring的相關配置
public class TestEmailController {
private MockHttpServletRequest request; //模擬request
private MockHttpServletResponse response; //模擬response
@Autowired
private EmailController ec; //這裏要注入controller 就是你調試要執行的controller
@Before //做初始化的工作
public void setUp(){
request = new MockHttpServletRequest();
request.setCharacterEncoding("UTF-8");
response = new MockHttpServletResponse();
}
@Test
public void emailDetail() { //用test標籤可以分開測試不同的 controller
try {
assertEquals("data_indox_details",ec.emailDetail(41, request, response)) ;
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void emailContent(){
try{
assertEquals("data_indox_details_tail",ec.emailContent(3, request, response)) ;
}catch (Exception e) {
e.printStackTrace();
}
}
}
另外,在@Test標籤可以做異常測試,比如
@Test(enabled=true,expectedExceptions = NullPointerException.class) //這裏預期拋出空指針異常
在@Test註解中可以做超時測試。如果運行時間超過指定的毫秒數,就測試失敗,這對於測試網絡鏈接類十分重要
@Test(timeOut=10)