May 15, 2021 jUnit
Test cases are executed using the JUnitCore class. J UnitCore is the skin class that runs the test. I t supports running JUnit 4 tests, JUnit 3.8.x tests, or their mixing. T o run a test from the command line, run java org.junit.runner.JUnitCore. For a test run that has only one run, you can use the static method runClasses.
Here's a statement from the org.junit.runner.JUnitCore class:
public class JUnitCore extends java.lang.Object
/*
* This class prints the given message on console.
*/
public class MessageUtil {
private String message;
//Constructor
//@param message to be printed
public MessageUtil(String message){
this.message = message;
}
// prints the message
public String printMessage(){
System.out.println(message);
return message;
}
}
In Directory C: You can JUNIT_WORKSPACE a java class file named TestJunit .java
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class TestJunit {
String message = "Hello World";
MessageUtil messageUtil = new MessageUtil(message);
@Test
public void testPrintMessage() {
assertEquals(message,messageUtil.printMessage());
}
}
Next, let's go to Directory C: JUNIT_WORKSPACE create a java class file named TestRunner.java to execute test cases, export the JUnitCore class, and use the runClasses() method to use the test class name as an argument.
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
public class TestRunner {
public static void main(String[] args) {
Result result = JUnitCore.runClasses(TestJunit.class);
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
System.out.println(result.wasSuccessful());
}
}
Use the javac command to compile the Test case and Test Runner classes.
C:\JUNIT_WORKSPACE>javac MessageUtil.java TestJunit.java TestRunner.java
Now run Test Runner and it will automatically run the test samples defined in the Test Case class.
C:\JUNIT_WORKSPACE>java TestRunner
Verify the output
Hello World
true