简体   繁体   English

使用Junit测试抛出异常的方法

[英]Test a method which throws an exception using Junit

I am trying to write a test case for a method which throws an exception based on certain logic. 我正在尝试为基于特定逻辑引发异常的方法编写测试用例。 However the test case fails as the expected exception and obtained exceptions are different. 但是,由于预期的异常和获得的异常不同,因此测试用例失败。

Method to test - 测试方法-

public void methodA (//parameters) throws ExceptionA
{
certainlogic=//call some method
if (certainlogic)
throw new ExceptionA(//exception details)
else
//code snippet
}

Test method - 测试方法 -

    @Test (expected=ExceptionA.class)
    public void testMethodA
    {
    try
    {
    when (//mock method).thenReturn(true);
    //call methodA
    }
    catch (ExceptionA e)
    {
    fail(e.printStackTrace(e));
    }
    }

I am receiving the below error - 我收到以下错误-

Unexpected exception, expected<cExceptionA> but was<java.lang.AssertionError>

How do I solve this issue? 我该如何解决这个问题?

You have to remove the catch in your test 您必须删除测试中的catch

@Test (expected=ExceptionA.class)
public void testMethod()
{
    when (//mock method).thenReturn(true);
    //call methodA
}

Otherwise you catch the ExceptionA and by calling fail you throw an AssertionError. 否则,您将捕获ExceptionA并通过调用fail引发AssertionError。 Obviously the AssertionError is not an ExceptionA and therefore your test fails. 显然, AssertionError不是ExceptionA ,因此您的测试失败。

You should remove the try-catch block entirely or at least the catch. 您应该完全删除try-catch块,或者至少删除catch。 The "expected = ExceptionA.class" tells junit to monitor for thrown exceptions, catch them and compare their class against the given class. “ expected = ExceptionA.class”告诉junit监视抛出的异常,捕获它们并将它们的类与给定的类进行比较。 If you catch the thrown exception, the @Test-annotated junit method cannot detect if such an exception is thrown. 如果捕获到引发的异常,则@Test注释的junit方法无法检测到是否引发了此类异常。 By calling fail(...) you implicitly throw an AssertionError which junit detects and thus your test fails because AssertionError.class != ExceptionA.class 通过调用fail(...),您隐式抛出了junit检测到的AssertionError,因此测试失败,因为AssertionError.class!= ExceptionA.class

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

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