繁体   English   中英

如何在测试用例中执行try块语句?

[英]How can I execute try block statements in test case?

如何在测试用例中执行try块语句? 我的测试用例总是难以捉摸。

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

@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对象,以查看其是否具有正确的消息和状态。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM