Search code examples
javajunitjunit4

Ignore JUnit tests if variable value is null


I have a JUnit test class which runs 15 tests. 5 of the tests are optional in that I only wish to run them if a particular variable gets initialized by an argument. If the variable value is null I'd like to ignore these tests. Is this possible and if so, how?


Solution

  • Approach 1:

    You can use JUnit-ext. It has RunIf annotation that performs conditional tests, like:

    @Test
    @RunIf(DatabaseIsConnected.class)
    public void calculateTotalSalary() {
        //your code there
    }
    
    class DatabaseIsConnected implements Checker {
       public boolean satisify() {
            return Database.connect() != null;
       }
    }
    

    Approach 2

    Another approach is to use Assume. 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. For example:

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

    Approach 3

    I think an another option for you may be to create an annotation to denote that the test needs to meet your custom criteria, then extend the default runner with your own and using reflection, base your decision on the custom criteria. It may look something like this:

        public class CustomRunner extends BlockJUnit4ClassRunner {
        public CTRunner(Class<?> klass) throws initializationError {
            super(klass);
        }
    
        @Override
        protected boolean isIgnored(FrameworkMethod child) {
            if(shouldIgnore()) {
                return true;
            }
            return super.isIgnored(child);
        }
    
        private boolean shouldIgnore(class) {
            /* some custom criteria */
        }
    }