任何人都可以建议我如何为下面的类编写JUnit:
@Controller
@RequestMapping(value = "/cutdata", consumes = "TEXT/XML")
public class CustController
{
Logger LOG = Logger.getLogger(CustController.class);
@Autowired
CustService custService;
@Autowired
MarCusService marCustService;
@Resource(name = "CustValidator")
private CusValidator validator;
@Resource(name = "cmsSiteService")
private CMSSiteService cmsSiteService;
protected CMSSiteService getCmsSiteService()
{
return cmsSiteService;
}
@RequestMapping(value = "/methodcall", method = RequestMethod.PUT)
public @ResponseBody ResponseEntity<?> methodCall(@RequestBody final CustDTO data)
throws WebServicesException
{
String statusCode = null;
try {
if (data.getGroup() != null && !data.getGroup().equals(String.valueOf(GroupEnum.ALL))) {
validator.validate(data);
}
} catch (WebServicesException e) {
return new ResponseEntity<>(e.getMessage(), HttpStatus.OK);
}
try
{
final CMSSiteModel site = cmsSiteService.getCurrentSite();
String currentSiteId=site.getUid() !=null ? site.getUid():"";
if(StringUtils.contains(currentSiteId,Config.getParameter("****.siteuid")))
{
statusCode = marCustService.processData(data);
}
else
{
statusCode = custService.processData1(data);
}
final String[] message = statusCode.split(":");
final String code = message[0];
final String statusMessage = message[1];
if (code.equalsIgnoreCase("200"))
{
return new ResponseEntity<>(statusMessage, HttpStatus.CREATED);
}
else if (code.equalsIgnoreCase("400"))
{
return new ResponseEntity<>(statusMessage, HttpStatus.BAD_REQUEST);
}
}
catch (final Exception e)
{
LOG.error("log ::" + e);
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
我是编写JUnit Test案例的新手,我需要帮助,比如如何编写或如何启动JUnit.
解决方法:
基本上,您需要使用Spring上下文来测试Controller类.
一个例子是这样的:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@WebAppConfiguration
public class CsrfShowcaseTests {
@Autowired
private WebApplicationContext context;
private MockMvc mvc;
@Before
public void setup() {
mvc = MockMvcBuilders
.webAppContextSetup(context)
.apply(springSecurity())
.build();
}
@Test
public void shouldTestMethodCall() {
mockMvc.perform(put("/methodcall"))
.andExpect(status.isOk());
}
}
通过此测试,您可以将测试扩展到您的流量.
如果您需要更多参考,可以查看Spring的文档here.