Assumptions in junit

Assumptions in JUnit allow you to specify the condition which should be met before executing certain tests. For example – some times it is important to ensure that service is running before executing the tests. If service is not running, tests should not be executed and failed. That’s when assumptions comes into picture. org.junit.Assume class provides below methods to check assumptions.
  • assumeTrue
  • assumeFalse
  • assumeNotNull
  • assumeThat
  • assumeNoException
In below example, since assumption fails, test is ignored. Notice that test does not fail but ignored.
 
package assumptions;

import org.junit.Assume;
import org.junit.Test;

/**
 * Created by Sagar on 30-04-2016.
 */
public class AssumeTest {

    @Test
    public void test1(){
        Assume.assumeTrue(ServiceCheck.isServiceRunning());
        System.out.println("This test will be executed only " +
                "when above assumption is true");
    }
}

class ServiceCheck{
    public static boolean isServiceRunning(){
        //code here to check if service is running or not
        //if service is running, true is returned else false is returned.
       return false;
    }
}

Here is the output of above code.
 
org.junit.AssumptionViolatedException: got: , expected: is

Web development and Automation testing

solutions delivered!!