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

时间:2022-05-07 05:07:30

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框架来测试