May 15, 2021 jUnit
JUnit is a regression testing framework that developers use to implement unit testing of applications, speed programming, and improve the quality of coding. The JUnit test framework makes it easy to combine any of the following:
The JUnit test framework has the following important features:
Test Tools is a set of fixed tools for baseline testing. T he purpose of the test tool is to ensure that tests can run in a shared and fixed environment, so that test results are repeatable. It includes:
Let's look at an example:
import junit.framework.*;
public class JavaTest extends TestCase {
protected int value1, value2;
// assigning the values
protected void setUp(){
value1=3;
value2=3;
}
// test method to add two values
public void testAdd(){
double result= value1 + value2;
assertTrue(result == 6);
}
}
A test suite means bundling several test cases and running them at the same time. I n JUnit, both @RunWith and @Suite are used to run test suites. The following are test classifications using TestJunit1 and TestJunit2:
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
//JUnit Suite Test
@RunWith(Suite.class)
@Suite.SuiteClasses({
TestJunit1.class ,TestJunit2.class
})
public class JunitTestSuite {
}
import org.junit.Test;
import org.junit.Ignore;
import static org.junit.Assert.assertEquals;
public class TestJunit1 {
String message = "Robert";
MessageUtil messageUtil = new MessageUtil(message);
@Test
public void testPrintMessage() {
System.out.println("Inside testPrintMessage()");
assertEquals(message, messageUtil.printMessage());
}
}
import org.junit.Test;
import org.junit.Ignore;
import static org.junit.Assert.assertEquals;
public class TestJunit2 {
String message = "Robert";
MessageUtil messageUtil = new MessageUtil(message);
@Test
public void testSalutationMessage() {
System.out.println("Inside testSalutationMessage()");
message = "Hi!" + "Robert";
assertEquals(message,messageUtil.salutationMessage());
}
}
The test runr is used to execute the test case. The following is an example of a situation where test classification is assumed to be established:
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());
}
}
Test classification is an important classification for writing and testing JUnit. Several important categories are as follows: