java JUnit 预期标记未按预期工作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1151237/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 15:22:39  来源:igfitidea点击:

JUnit expected tag not working as expected

javaunit-testingjunitjunit4

提问by Ben S

I have the following test case in eclipse, using JUnit 4 which is refusing to pass. What could be wrong?

我在 Eclipse 中有以下测试用例,使用拒绝通过的 JUnit 4。可能有什么问题?

@Test(expected = IllegalArgumentException.class)
public void testIAE() {
    throw new IllegalArgumentException();
}

This exact testcase came about when trying to test my own code with the expected tag didn't work. I wanted to see if JUnit would pass the most basic test. It didn't.

这个确切的测试用例是在尝试使用预期标签测试我自己的代码不起作用时出现的。我想看看 JUnit 是否会通过最基本的测试。它没有。

I've also tested with custom exceptions as expected without luck.

我还按预期测试了自定义异常,但没有运气。

Screenshot:Screenshot

截屏:截屏

回答by Yishai

The problem is that your AnnounceThreadTest extends TestCase. Because it extends TestCase, the JUnit Runner is treating it as a JUnit 3.8 test, and the test is running because it starts with the word test, hiding the fact that the @Test annotiation is in fact not being used at all.

问题是您的AnnounceThreadTest 扩展了TestCase。因为它扩展了 TestCase,所以 JUnit Runner 将其视为 JUnit 3.8 测试,并且该测试正在运行,因为它以单词 test 开头,隐藏了事实上根本没有使用 @Test 注释的事实。

To fix this, remove the "extends TestCase" from the class definition.

要解决此问题,请从类定义中删除“extends TestCase”。

回答by HsYoo

Instead of removing extends TestCase , you can add this to run your test case with Junit4 which supports annotation.

您可以添加它以使用支持注释的 Junit4 运行您的测试用例,而不是删除 extends TestCase 。

@RunWith(JUnit4.class)

@RunWith(JUnit4.class)

回答by duffymo

Just ran this in IntelliJ using JUnit 4.4:

刚刚使用 JUnit 4.4 在 IntelliJ 中运行它:

   @Test(expected = IllegalArgumentException.class)
   public void testExpected()
   {
       throw new IllegalArgumentException();
   }

Passes perfectly.

完美通过。

Rebuild your entire project and try again. There's something else that you're doing wrong. JUnit 4.4 is working as advertised.

重建整个项目并重试。还有其他事情你做错了。JUnit 4.4 正像宣传的那样工作。