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

时间:2014-10-03 09:17:05

标签: java unit-testing junit mockito

如何在测试用例中执行try block语句?我的测试用例总是用于阻止。

我需要模拟问题bean,PostingResult,Question,dao all?我很迷惑。我如何测试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;
    }

1 个答案:

答案 0 :(得分:1)

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

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

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