设为首页 加入收藏

TOP

如何使用Junit测试使用Spring框架的代码(一)
2014-11-24 12:02:24 来源: 作者: 【 】 浏览:97
Tags:如何 使用 Junit 测试 Spring 框架 代码
1. 测试一般的类
写一个抽象类,所有的测试类都继承它
[java]
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath*:application-context-test.xml" })
public abstract class AbstractJUnit {
}
[java]
public class OriginAndDestinationServiceTestCase extends AbstractJUnit {
@Autowired
private IOriginAndDestinationService service;
private OriginADestinationRequestDTO request;
@Before
public void init() {
this.request = new OriginADestinationRequestDTO();
this.request.setBrand("KA");
this.request.setBookingFlow("REV");
this.request.setLocale("en_HK");
this.request.setOrigin("HKG");
this.request.setSector(0);
this.request.setCorrelationInfo(new CorrelationInfo("aaaa", "bbbb", "cccc"));
}
@Test
public void testService() {
OriginADestinationResponseDTO response = this.service.invoke(this.request);
Assert.assertNotNull(response);
}
}
2. 测试Controller, 这里使用的是Spring MVC框架,测试Action或是servlet也差不多
还是弄一个抽象类
[java]
@ContextConfiguration(locations = { "classpath*:application-context-junit.xml",
"file:src/main/webapp/WEB-INF/spring3-servlet.xml" })
public class JUnitActionBase extends AbstractJUnit4SpringContextTests {
/**
* default http port.
*/
private static final int DEFAULT_PORT = 80;
/**
* DefaultAnnotationHandlerMapping.
*/
@Resource(type = DefaultAnnotationHandlerMapping.class)
protected HandlerMapping handlerMapping;
/**
* AnnotationMethodHandlerAdapter.
*/
@Resource(type = AnnotationMethodHandlerAdapter.class)
protected HandlerAdapter handlerAdapter;
/**
* Simulate Request to URL appoint by MockHttpServletRequest.
*
* @param request
* HttpServletRequest
* @param response
* HttpServletResponse
* @return ModelAndView
* @throws Exception
* runtimeException
*/
public final ModelAndView excuteAction(final HttpServletRequest request, final HttpServletResponse response)
throws Exception {
HandlerExecutionChain chain = this.handlerMapping.getHandler(request);
final ModelAndView model = this.handlerAdapter.handle(request, response, chain.getHandler());
return model;
}
/**
* Simulate Request to URL appoint by MockHttpServletRequest, default POST, port 80.
*
* @param url
* requestURL
* @param objects
* parameters
* @return ModelAndView
*/
public final ModelAndView excuteAction(final String url, final Object[]... objects) {
return this.excuteAction("POST", url, JUnitActionBase.DEFAULT_PORT, objects);
}
/**
* Simulate Request to URL appoint by MockHttpServletRequest, default POST.
*
* @param url
* requestURL
* @param port
* int
* @param objects
* parameters
* @return ModelAndView
*/
public final ModelAndView excuteAction(final String url, final int port, final Object[]...
首页 上一页 1 2 下一页 尾页 1/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇利用JDBC连接取数据并导入到EXCEL.. 下一篇 Java乔晓松-ajax的概述和XMLHTTP..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: