gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:06:01 25 4
gpt4 key购买 nike

谁能建议我如何为下面的类编写 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 测试用例的新手,我需要帮助,例如如何编写或如何启动 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 .

关于java - 如何为 Rest 调用编写 Junit 测试用例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48135265/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com