Conditionally ignoring tests in JUnit 4

后端 未结 5 1102
醉酒成梦
醉酒成梦 2020-11-22 13:38

OK, so the @Ignore annotation is good for marking that a test case shouldn\'t be run.

However, sometimes I want to ignore a test based on runtime inform

5条回答
  •  醉梦人生
    2020-11-22 14:33

    The JUnit way is to do this at run-time is org.junit.Assume.

     @Before
     public void beforeMethod() {
         org.junit.Assume.assumeTrue(someCondition());
         // rest of setup.
     }
    

    You can do it in a @Before method or in the test itself, but not in an @After method. If you do it in the test itself, your @Before method will get run. You can also do it within @BeforeClass to prevent class initialization.

    An assumption failure causes the test to be ignored.

    Edit: To compare with the @RunIf annotation from junit-ext, their sample code would look like this:

    @Test
    public void calculateTotalSalary() {
        assumeThat(Database.connect(), is(notNull()));
        //test code below.
    }
    

    Not to mention that it is much easier to capture and use the connection from the Database.connect() method this way.

提交回复
热议问题