Java Unit Testing with JUnit
Image Source: https://junit.org/
In this blog post, I have written about unit testing and use of JUnit for Java programming. The first section of this blog post includes the unit testing example without using any IDE and second section includes the unit testing example using IntelliJ IDEA.
JUnit is a unit testing framework for Java programming. JUnit is open source and popular unit testing framework for Java programming.
I = PTR / 100
Unit Testing ( No IDE)
- Download JUnit.jar and Hamcrest-core.jar.
- junit-4.12.jar ( link ) (latest version available at time of the post)
- hamcrest-core-1.3.jar ( link ) (latest version available at time of the post)
- Create a project directory, copy these jars to the newly created directory. All java files and classes are stored inside the directory.
- Create Calculator.java, that includes the main logic of calculating the Interest.
- Create TestCalculator.java, this is where you compare the results.
- Create TestRunner.java, this includes the test classes to perform test.
- Compile with JUnit and hamcrest.
javac -classpath junit-4.12.jar;hamcrest-core-1.3.jar;. Calculator.java TestCalculator.java TestRunner.java
- Now run, reminder : TestRunner includes the main method,
java -classpath junit-4.12.jar;hamcrest-core-1.3.jar;. TestRunner
- And yey, test is successful, now try to change some values.
public class Calculator{
// default values
double p = 0.0;
double t = 0.0;
double r = 0.0;
// constructor that updates the values
public Calculator(double p, double t, double r){
this.p = p;
this.t = t;
this.r = r;
}
// method that calculates the interest
public double calculateInterest(){
return p*t*r / 100;
}
}
import org.junit.Test;
import org.junit.Before;
import static org.junit.Assert.assertEquals;
public class TestCalculator{
Calculator calculator = null;
// values for your test case
double p = 10000.0;
double t = 1.0;
double r = 10.0;
// this run at every test
@Before
public void setUp() throws Exception{
calculator = new Calculator(p, t, r);
}
// TEST
@Test
public void testCalculateInterest(){
assertEquals(1000.0, calculator.calculateInterest(), 0.0);
}
}
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
public class TestRunner{
public static void main(String[] str){
// Run test classes and grab result
Result result = JUnitCore.runClasses(TestCalculator.class);
// Test result
System.out.println(result.wasSuccessful());
// print the failure message if failure
for(Failure failure : result.getFailures()){
// print string
System.out.println(failure.toString());
}
}
}
Continue (Unit Testing using IntelliJ)
References:

Comments
Post a Comment