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フレームワークに合わせてテストすることもできます