如何使用Junit测试使用Spring框架的代码

1. 测试一般的类

    写一个抽象类,所有的测试类都继承它

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath*:application-context-test.xml" })
public abstract class AbstractJUnit {
}

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也差不多 

     还是弄一个抽象类

@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[]... objects) {
        return this.excuteAction("POST", url, port, objects);
    }

    /**
     * Simulate Request to URL appoint by MockHttpServletRequest.
     * 
     * @param method
     *        POST/GET
     * @param url
     *        requestURL
     * @param port
     *        int
     * @param objects
     *        parameters
     * @return ModelAndView
     */
    public final ModelAndView excuteAction(final String method, final String url, final int port,
        final Object[]... objects) {
        MockHttpServletRequest request = new MockHttpServletRequest(method, url);
        MockHttpServletResponse response = new MockHttpServletResponse();
        request.setServerPort(port);
        request.setLocalPort(port);
        if (objects != null) {
            for (Object[] object : objects) {
                if (object != null && object.length == 2) {
                    request.addParameter(object[0].toString(), object[1].toString());
                }
            }
        }
        MockHttpSession session = new MockHttpSession();
        request.setSession(session);
        try {
            return this.excuteAction(request, response);
        } catch (Exception e) {
            e.printStackTrace();
            InfoLogUtil.error(e.toString());
        }
        return null;
    }
}

测试类

public class LocationInfoTest extends JUnitActionBase {

    /**
     * TODO: write description for this method.
     */
    @Test
    public void testKeepAlive() {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("ACTION", "KEEP_ALIVE");
        this.excuteAction("/IBEFacade", 8080, paramMap);
    }

    /**
     * TODO: write description for this method.
     */
    @Test
    public void testLocationInfo() {
        this.excuteAction("/IBEFacade", 8080, new Object[]{"ACTION", "LOCATION_INFO"});
    }
}

另外还可以配合easymock/powermock框架来测试


   

  • 14
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值