gpt4 book ai didi

java - 如何在测试用例中执行 try block 语句?

转载 作者:行者123 更新时间:2023-12-01 12:28:08 24 4
gpt4 key购买 nike

如何在测试用例中执行try block 语句?我的测试用例总是进入 catch block 。

我需要模拟问题bean、PostingResult、Question、dao 全部吗?我很困惑。我如何测试 if/else ?问题类的两个字段是枚举。

@Controller
@RequestMapping("/questionservice")
public class QuestionServiceController {

private static Log log = LogFactory.getLog(QuestionServiceController.class);
private final static Long SUCCESS = 000l;
private final static Long FAILURE = 999l;

@Autowired
QuestionAnswerDao questionAnswerDao;
@Autowired
QuestionAnswerDirectoryDao questionAnswerDirectoryDao;

@RequestMapping(value = "/postquestion", method = RequestMethod.POST)
public @ResponseBody PostingResult postQuestion(@RequestBody QuestionBean questionBean) {
System.out.println("In....");
PostingResult response = new PostingResult();
if (log.isDebugEnabled()) {
log.debug("QuestionBean: " + questionBean);
}
try {
System.out.println("in try");
Question question = questionAnswerDao.postQuestion(getQuestion(questionBean));
System.out.println("question"+question);
if (null != question) {
response.setStatus(SUCCESS);
response.setStatusMessage("Successfully saved..");
} else {
response.setStatusMessage("Question is null..");
response.setStatus(FAILURE);
}
} catch (Exception exp) {
if (log.isErrorEnabled()) {
log.error("Exception in processing " + questionBean + "; Exception: " + exp.toString());
}
response.setStatusMessage("Saving failed.. Exception: " + exp.toString());
response.setStatus(FAILURE);
}
return response;
}

最佳答案

看起来您需要模拟 questionAnswerDao。然后告诉 Mockito 在调用 postQuestion() 时抛出异常。

when(questionAnswerDao.postQuestion(/* specify args here */))
.thenThrow(new SomeException());

然后您可以测试response对象以查看它是否具有正确的消息和状态。

关于java - 如何在测试用例中执行 try block 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26176347/

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