java – 如何为Rest调用编写Junit测试用例?

任何人都可以建议我如何为下面的类编写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.

上一篇:如何在Gradle中的JUnit平台中拥有两组测试


下一篇:java – JUnit说我的测试方法“无法解析为一个独特的方法”