Junit验证命令执行

时间:2014-03-26 16:08:03

标签: java junit

我有测试用例:

@Test(expected = IllegalArgumentException.class)
public void testRunWithLessThanTwoParameters_IllegalArgumentException() 
    throws Exception {

    final String[] args = { "Less Number of parameters" };
    command = spy(new GenerateSummaryReportCommand());      
    commandLine = new PosixParser().parse(new Options(),Arrays.copyOfRange(args, 0, args.length));
    assertEquals(0, command.run(commandLine));      
    verify(command, times(1)).usage();
}

我想知道在assertEqual语句

之后是否会执行verify

1 个答案:

答案 0 :(得分:0)

我认为parse正在抛出IllegalArgumentException。如果是这种情况,assertEqualsverify都不会被执行,因为异常是抛出它们。抛出异常后进行验证的方法是将验证放在catch块中。

@Test(expected = IllegalArgumentException.class)
public void testRunWithLessThanTwoParameters_IllegalArgumentException() 
   throws Exception {

     final String[] args = { "Less Number of parameters" };
     command = spy(new GenerateSummaryReportCommand());      

   try{
     commandLine = new PosixParser().parse(new Options(),Arrays.copyOfRange(args, 0, args.length));
   }catch (Exception e){
     assertEquals(0, command.run(commandLine));      
     verify(command, times(1)).usage();

      throw e;
   }
 }

请注意,我重新抛出异常以允许进行expected检查。