2014-10-03 4 views
0

테스트 사례에서 try 블록 문을 실행하려면 어떻게해야합니까? 내 테스트 케이스는 항상 블록을 잡으려고합니다.테스트 사례에서 try 블록 문을 실행하려면 어떻게해야합니까?

질문 빈, PostingResult, 질문, DAO 모두 모의해야합니까? 나는 혼란 스럽다. if/else를 어떻게 테스트 할 수 있습니까? 질문 클래스 2 필드는 열거 형입니다.

@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

questionAnswerDao을 조롱해야합니다. 그런 다음 postQuestion()이 호출 될 때 Mockito에게 예외가 발생하도록 명령하십시오.

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

그럼 당신은 올바른 메시지와 상태가 있는지 확인하기 위해 response 객체를 테스트 할 수 있습니다.

+0

if/else 조건은 어떻게됩니까? 나는 그걸 가지 않아야하지 않니? – abc

+0

@ripu 너의 조롱 된 객체에서 null을 돌려줌으로써 그것을 테스트 할 수도있다. –

+0

if/else 조건을 입력 할 수 없습니다. @Mock \t QuestionAnswerDaoImpl(); Mockito.when (questionAnswerDao.postQuestion (question)). thenReturn (null); 이것은 항상 NPE를 반환합니다. 따라서 catch() 블록이 실행 중이다. 도와주세요. – abc

관련 문제