Junit is a unit testing framework for the Java programming language. If you want to read about best practices followed for junit testing then here is an excellent guide for your reference.
In this post, I am writing about writing junit testcases which will run only when a certain condition is met on runtime. For example, I want to run a testcase only when some other network service is up. I do not want to fail my test, if service is down.
In junit, above is possible with use of “org.junit.Assume“. Below is a sample usage:
@Test public void testIfVersioonGreaterThan4() { String versionNumber = "7"; //Get it from configuration on runtime Assume.assumeTrue(Integer.valueOf(versionNumber) == 7); System.out.println("Test executed"); }
Above testcase will execute only when the application version is greater than 7. Its actually a great feature which enables us to write feature specific test cases without much worry.
When above testcase is executed, if application version is greater than 7 or less than 7, testcase is ignored just it is using @Ignore annotation. Some IDEs might show like they executed the testcase but they actually didn’t and just ignored. You can verify by watching logs.
If you want to ignore all testcases in a single java class then it can be used in @Before annotated method. All testcases will be ignored in such way.
package com.howtodoinjava.test.junit; import org.junit.Assume; import org.junit.Before; import org.junit.Test; public class JunitAssumptionTest { @Before public void setUp() { String versionNumber = "7"; //Get it from configuration on runtime Assume.assumeTrue(Integer.valueOf(versionNumber) == 7); } @Test public void testIfVersioonGreaterThan4() { System.out.println("Test executed"); } }
Assumption based testcases can be useful in following scenarios:
- Running testcases for specific application version(s)
- Running testcases only when certain network resource (or any external service) is available
- Running testcases in a certain locale only
- Running testcases only under certain execution environment
There might be other such cases as per need. Let me know if you have any question?
Happy Learning !!
Comments