简体   繁体   English

junit testing - assertEquals异常

[英]junit testing - assertEquals for exception

How can I use assertEquals to see if the exception message is correct? 如何使用assertEquals查看异常消息是否正确? The test passes but I don't know if it hits the correct error or not. 测试通过,但我不知道它是否达到了正确的错误。

The test I am running. 我正在运行的测试。

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

The method being tested. 正在测试的方法。

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;       
}

} }

Thanks for the help. 谢谢您的帮助。

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() );
}   

The assertEquals in your example would be comparing the return value of the method call to the expected value, which isn't what you want, and of course there isn't going to be a return value if the expected exception occurs. 您的示例中的assertEquals将比较方法调用的返回值与期望值,这不是您想要的,当然,如果发生预期的异常,则不会返回值。 Move the assertEquals to the catch block: 将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());
    }        
}

Works perfectly for me. 适合我。

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

if assertEquals fails ComparisonFailure will handle it 如果assertEquals失败,ComparisonFailure将处理它

Java 8 solution Java 8解决方案

Here is a utility function that I wrote: 这是我写的一个实用函数:

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 ) 摘自我的博客

Use it as follows: 使用方法如下:

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

Also, if you would like to read some reasons why you should not want to assertTrue that the message of your exception is equal to a particular value, see this: https://softwareengineering.stackexchange.com/a/278958/41811 另外,如果你想阅读一些原因, 应该assertTrue你异常的消息是等于一个特定的值时,看到这一点: https://softwareengineering.stackexchange.com/a/278958/41811

This is nice library that allows asserting exceptions in a clean way. 这是一个很好的 ,允许以干净的方式断言异常。

Example: 例:

// 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();

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

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