简体   繁体   English

Java:使用Junit 3进行异常测试

[英]Java: Exception testing with Junit 3

I would like to write a test for IndexOutOfBoundsException . 我想为IndexOutOfBoundsException编写一个测试。 Keep in mind that we are supposed to use JUnit 3. 请记住,我们应该使用JUnit 3。

My code: 我的代码:

public boolean ajouter(int indice, T element) {
    if (indice < 0 || indice > (maListe.size() - 1)) {
        throw new IndexOutOfBoundsException();
    } else if (element != null && !maListe.contains(element)) {
        maListe.set(indice, element);
        return true;
    }
}

After some research, I found that you can do this with JUnit 4 using @Test(expected = IndexOutOfBoundsException.class) but no where did I find how to do this in JUnit 3. 经过一些研究,我发现你可以使用@Test(expected = IndexOutOfBoundsException.class)在JUnit 4中执行此操作,但是我没有在JUnit 3中找到如何执行此操作的位置。

How can I test this using JUnit 3? 如何使用JUnit 3进行测试?

Testing exceptions in JUnit 3 uses this pattern: 在JUnit 3中测试异常使用以下模式:

try {
     ... code that should throw an exception ...

     fail( "Missing exception" );
} catch( IndexOutOfBoundsException e ) {
     assertEquals( "Expected message", e.getMessage() ); // Optionally make sure you get the correct message, too
}

The fail() makes sure you get an error if the code doesn't throw an exception. 如果代码没有抛出异常, fail()会确保您收到错误。

I use this pattern in JUnit 4 as well since I usually want to make sure the correct values are visible in the exception message and @Test can't do that. 我在JUnit 4中也使用这种模式,因为我通常希望确保在异常消息中可以看到正确的值,而@Test不能这样做。

Basically, you need to call your method and fail if it doesn't throw the right exception - or if it throws anything else: 基本上,您需要调用您的方法,如果它没有抛出正确的异常,则会失败 - 或者如果它抛出任何其他东西:

try {
  subject.ajouter(10, "foo");
  fail("Expected exception");
} catch (IndexOutOfBoundException expect) {
  // We should get here. You may assert things about the exception, if you want.
}

A simple solution is to add a try catch to the unittest and let the test fail when the exception isn't thrown 一个简单的解决方案是向unittest添加try catch,并在未抛出异常时让测试失败

public void testAjouterFail() {
  try {
    ajouter(-1,null);
    JUnit.fail();
  catch (IndexOutOfBoundException()) {
    //success
  }
}

One thing you can do is use a boolean to run the test to completion and then you can use assert to validate the exception was thrown: 您可以做的一件事是使用布尔运行测试完成,然后您可以使用assert来验证抛出的异常:

boolean passed = false;
try
{
    //the line that throws exception
    //i.e. illegal argument exception
    //if user tries to set the property to null:
    myObject.setProperty(null);
}
catch (IllegalArgumentException iaex)
{
    passed = true;
}
assertTrue("The blah blah blah exception was not thrown as expected"
              , passed);

By using this test, your test will never fail to execute and you can validate that a specific exception type is thrown. 通过使用此测试,您的测试将永远不会执行,您可以验证是否抛出了特定的异常类型。

In your test method, call ajouter() inside a try .. catch block, giving a value of indice that should cause the exception to be thrown, with 在你的测试方法中,在try .. catch块中调用ajouter() ,给出一个应该引起异常的indice值,

  • a catch clause that catches IndexOutOfBoundsException : in that case return from your test method and thus indicate a pass. 捕获IndexOutOfBoundsExceptioncatch子句:在这种情况下从测试方法返回并因此指示传递。
  • a second catch clause that catches Throwable : in that case declare a failure (call fail() ), because the wrong kind of exception was thrown 捕获Throwable的第二个catch子句:在这种情况下声明失败(调用fail() ),因为抛出了错误的异常类型
  • after the try .. catch declare a failure (call fail() ), because no exception was thrown. try ..之后, catch声明失败(调用fail() ),因为没有抛出异常。

Extending @Aaron's solution with some (static import) syntactic sugar allows writing: 使用一些(静态导入)语法糖扩展@Aaron的解决方案允许编写:

    expected(MyException.class,
        new Testable() {
            public void test() {
            ... do thing that's supposed to throw MyException ...
            }
        });

Testable is like a Runnable which uses test() signature throwing Throwable. Testable就像一个Runnable,它使用test()签名抛出Throwable。

public class TestHelper {
    public static void expected(Class<? extends Throwable> expectedClass, Testable testable) {
        try {
            testable.test();
            fail("Expected "+ expectedClass.getCanonicalName() +" not thrown.");
        } catch (Throwable actual) {
            assertEquals("Expected "+ expectedClass.getCanonicalName() +" to be thrown.", expectedClass, actual.getClass());
        }
    }

    interface Testable {
        public void test() throws Throwable;
    }
}

You could add checking of the exception message as required. 您可以根据需要添加对异常消息的检查。

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

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