JUnit expected tag not working as expected

自古美人都是妖i 提交于 2019-11-27 11:32:30

问题


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

@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.

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

Screenshot:


回答1:


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.

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




回答2:


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

@RunWith(JUnit4.class)




回答3:


Just ran this in IntelliJ using JUnit 4.4:

   @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.



来源:https://stackoverflow.com/questions/1151237/junit-expected-tag-not-working-as-expected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!