I have two classes Calculator1 and Calculator2 which are in the package called com.zzy.junit.user under the src folder. I use myeclipse to create two test classes to test them respectively. When I execute the one test class among them, how does Junit4 know which class is tested?
Class 1
package com.zzy.junit.user;
public class Calculator1 {
private int a;
private int b;
public Calculator1(int a,int b)
{
this.a = a;
this.b = b;
}
public int add()
{
return a+b;
}
}
Class 2
package com.zzy.junit.user;
public class Calculator2{
public int divide(int a,int b)
{
return a/b;
}
}
And two test classes as follows:
They are both in the src folder called test
Test Class 1
package com.zzy.junit.user;
import static org.junit.Assert.*;
import static org.hamcrest.Matchers.*;
import org.junit.Test;
public class TestCalculator1 {
@Test
public void testAdd() {
Calculator1 s = new Calculator1(3,6);
int z = s.add();
assertThat(z,is(9));
}
}
Test Class 2
package com.zzy.junit.user;
import static org.junit.Assert.*;
import static org.hamcrest.Matchers.*;
import org.junit.Test;
public class TestCalculator2 {
@Test
public void testDivide() {
TestCalculator2 t = new TestCalculator2();
int z = t.divide(4, 2);
assertThat(z,is(2));
}
}
I want to know if I execute the test class called TestCalculator2, how does Junit4 know I do want to test Calculator1 class. Is it related to the name of the test class?
JUnit is a framework for executing tests that can pass or fail. The fact that a single test typically focusses on a single class is a convention observed by most Java programmers. JUnit4 doesn’t know which classes are being tested, it merely executes all methods annotated with
@Test.