【问题标题】:junit testing - assertEquals for exceptionjunit 测试 - 异常的 assertEquals
【发布时间】:2012-04-13 20:47:20
【问题描述】:

如何使用 assertEquals 来查看异常消息是否正确? 测试通过了,但我不知道它是否遇到了正确的错误。

我正在运行的测试。

@Test
public void testTC3()
{
    try {
    assertEquals("Legal Values: Package Type must be P or R", Shipping.shippingCost('P', -5));
    } 
    catch (Exception e) {
    }        
}

正在测试的方法。

public static int shippingCost(char packageType, int weight) throws Exception
{
    String e1 = "Legal Values: Package Type must be P or R";
    String e2 = "Legal Values: Weight < 0";
    int cost = 0;
        if((packageType != 'P')&&(packageType != 'R'))
        {
             throw new Exception(e1);
        }

        if(weight < 0)
        {
             throw new Exception(e2);
        }        
         if(packageType == 'P')
         {
             cost += 10;
         }
         if(weight <= 25)
         {   
             cost += 10;
         }
         else
         {
            cost += 25;
         }
         return cost;       
}

}

感谢您的帮助。

【问题讨论】:

    标签: java exception junit exception-handling junit4


    【解决方案1】:
    try {
        assertEquals("Legal Values: Package Type must be P or R", Shipping.shippingCost('P', -5));
        Assert.fail( "Should have thrown an exception" );
    } 
    catch (Exception e) {
        String expectedMessage = "this is the message I expect to get";
        Assert.assertEquals( "Exception message must be correct", expectedMessage, e.getMessage() );
    }   
    

    【讨论】:

    • 谢谢!简单且帮助很大
    【解决方案2】:

    您示例中的 assertEquals 会将方法调用的返回值与预期值进行比较,这不是您想要的,如果发生预期的异常,当然不会有返回值。将 assertEquals 移动到 catch 块:

    @Test
    public void testTC3()
    {
        try {
            Shipping.shippingCost('P', -5);
            fail(); // if we got here, no exception was thrown, which is bad
        } 
        catch (Exception e) {
            final String expected = "Legal Values: Package Type must be P or R";
            assertEquals( expected, e.getMessage());
        }        
    }
    

    【讨论】:

    • 没有看到你的答案,看了你的回复后我重新编写了代码。谢谢!
    【解决方案3】:

    非常适合我。

    try{
        assertEquals("text", driver.findElement(By.cssSelector("html element")).getText());
        }catch(ComparisonFailure e){
            System.err.println("assertequals fail");
        }
    

    如果 assertEquals 失败,ComparisonFailure 将处理它

    【讨论】:

      【解决方案4】:

      Java 8 解决方案

      这是我写的一个实用函数:

      public final <T extends Throwable> T expectException( Class<T> exceptionClass, Runnable runnable )
      {
          try
          {
              runnable.run();
          }
          catch( Throwable throwable )
          {
              if( throwable instanceof AssertionError && throwable.getCause() != null )
                  throwable = throwable.getCause(); //allows "assert x != null : new IllegalArgumentException();"
              assert exceptionClass.isInstance( throwable ) : throwable; //exception of the wrong kind was thrown.
              assert throwable.getClass() == exceptionClass : throwable; //exception thrown was a subclass, but not the exact class, expected.
              @SuppressWarnings( "unchecked" )
              T result = (T)throwable;
              return result;
          }
          assert false; //expected exception was not thrown.
          return null; //to keep the compiler happy.
      }
      

      (taken from my blog)

      如下使用:

      @Test
      public void testThrows()
      {
          RuntimeException e = expectException( RuntimeException.class, () -> 
              {
                  throw new RuntimeException( "fail!" );
              } );
          assert e.getMessage().equals( "fail!" );
      }
      

      另外,如果您想了解一些原因您应该想要assertTrue您的异常消息等于特定值,请参阅这个:https://softwareengineering.stackexchange.com/a/278958/41811

      【讨论】:

        【解决方案5】:

        这很好library,它允许以干净的方式断言异常。

        例子:

        // given: an empty list
        List myList = new ArrayList();
        
        // when: we try to get the first element of the list
        when(myList).get(1);
        
        // then: we expect an IndexOutOfBoundsException
        then(caughtException())
                .isInstanceOf(IndexOutOfBoundsException.class)
                .hasMessage("Index: 1, Size: 0")
                .hasNoCause();
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2011-01-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-02-19
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多