简体   繁体   English

Android JUnit:如何使异常导致测试用例通过(@Test注释)

[英]Android JUnit: How to have an exception cause a test case to pass (@Test annotation)

I'm trying to write some JUnit tests for an Android application. 我正在尝试为Android应用程序编写一些JUnit测试。

I've read online that to have a unit test pass if it throws an exception, you would use the @Test annotation like this 我在网上看过如果它抛出一个异常会有一个单元测试通过,你会使用像这样的@Test注释

@Test(expected = NullPointerException.class)
public void testNullValue() throws Throwable
{
    Object o = null;
    o.toString();
}

but Eclipse is telling me that this annotation doesn't exist. 但是Eclipse告诉我这个注释不存在。 How can I fix this? 我怎样才能解决这个问题? If I run the test, it runs fine and fails as expected but obviously I want it to fail (and thus actually pass) :) 如果我运行测试,它运行正常并按预期失败但显然我希望它失败(因此实际上通过):)

You can always bypass it manually: 您始终可以手动绕过它:

public void testNullValue()
{
    try {
       Object o = null;
       o.toString();
       fail("Expected NullPointerException to be thrown");
    } catch (NullPointerException e) {
       assertTrue(true);
    }
}

我认为应该是:

@Test(expected=NullPointerException.class)
  1. Double check the JUnit version you are using 仔细检查您正在使用的JUnit版本
  2. Do not use the JUnit that eclipse provides (Indigo) but import manually a JUnit 4.9 manually 不要使用eclipse提供的JUnit(Indigo),而是手动导入JUnit 4.9

The error is that "mysterious" error that has not an easy or immediate answer, I am only trying ideas 错误是“神秘”的错误,没有一个简单或立即的答案,我只是尝试的想法

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

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