JUnit Testing with Intellij IDE
Image: www.wikipedia.org
This is Intellij IDE JUnit Testing tutorial. You can refer to (Java Unit Testing with JUnit ) for original.
For this unit testing, I have created new project, no libraries, no template.
- Create new directory "test", right click on project > add > directory.
- Mark the directory as test sources root.
- Create Calculator class, the class is created as , right click on project > add > java class.
paste the code
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; } } - Create test class for Calculator, press alt & enter on class name > create test.
Configure JUnit like as thisFix and download library And the newly created testClass (CalculatorTest) will look like thisimport org.junit.After; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; public class CalculatorTest { Calculator calculator = null; // values for your test case double p = 10000.0; double t = 1.0; double r = 10.0; @Before public void setUp() throws Exception { calculator = new Calculator(p, t, r); } @After public void tearDown() throws Exception { } @Test public void calculateInterest() { assertEquals(1000.0, calculator.calculateInterest(), 0.0); } } - Create a TestRunner class inside test directory. This will be our entry point to perform all test, paste.
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(CalculatorTest.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()); } } } - Yey, test success.





Comments
Post a Comment