JUnit 4.x – Testing Framework : JUnit Example
JUnit First Example |
Calculator class that helps to add two number.
Calculator.java
package com.javaskool;
public class Calculator {
public int add(int a,int b)
{
return a+b;
}
}
CalculatorMesg class that helps to display message.
CalculatorMesg.java
package com.javaskool;
public class CalculatorMesg {
public String addMesg()
{
return "Addition";
}
}
CalcTest class that helps to test my Calculator class.
CalcTest.java
package com.javaskool;
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class CalcTest {
@Before
public void setUp() throws Exception {
System.out.println("Before");
}
@After
public void tearDown() throws Exception {
System.out.println("After");
}
@Test
public void testAdd() {
Calculator c=new Calculator();
int x=c.add(50, 20);
assertEquals(70, x);
System.out.println(x);
}
}
CalcMesgTest class that helps to test my CalculatorMesg class.
CalcMesgTest.java
package com.javaskool;
import static org.junit.Assert.*;
import org.junit.Test;
public class CalcMesgTest {
@Test
public void test() {
CalculatorMesg m=new CalculatorMesg();
String s=m.addMesg();
assertEquals("Addition", s);
System.out.println(s +" : ");
}
}
MyJUnitTestSuite class using annotation that helps to test both Calculator and CalculatorMesg class together as test suite.
MyJUnitTestSuite.java
package com.javaskool;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses({
CalcMesgTest.class,
CalcTest.class
})
public class MyJUnitTestSuite {
}
MyTestRunner Java Application that helps to test both Calculator and CalculatorMesg class together as test suite.
MyTestRunner.java
package com.javaskool;
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
public class MyTestRunner {
public static void main(String[] args) {
Result result = JUnitCore.runClasses(MyJUnitTestSuite.class);
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
System.out.println(result.wasSuccessful()); //return true or false
}
}
Downloads Examples |
Recent Comments