通过运行方法来测试您的方法(在 Eclipse 中,右击,选择 Run as → JUnit Test)。
//for normal addition
@Test
public void testAdd1Plus1()
{
int x = 1 ; int y = 1;
assertEquals(2, myClass.add(x,y));
}
Add other cases as desired.
Test that your binary sum does not throw a unexpected exception if there is an integer overflow.
Test that your method handles Null inputs gracefully (example below).
//if you are using 0 as default for null, make sure your class works in that case.
@Test
public void testAdd1Plus1()
{
int y = 1;
assertEquals(0, myClass.add(null,y));
}
public class Math {
int a, b;
Math(int a, int b) {
this.a = a;
this.b = b;
}
public int add() {
return a + b;
}
}
5-点击文件-> 新建-> JUnit 测试用例。
选中 setUp ()并单击 Finish。 SetUp ()将是您初始化测试的位置。
点击确定。
这里,我简单地加上7和10。所以,我希望答案是17。像这样完成你的测试课程:
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class MathTest {
Math math;
@Before
public void setUp() throws Exception {
math = new Math(7, 10);
}
@Test
public void testAdd() {
Assert.assertEquals(17, math.add());
}
}
9-写单击您的测试类在包资源管理器中,然后单击 Run as-> JUnit Test。
这是测试的结果。
情报:
注意,我在截图中使用了 IntelliJ IDEA 社区2020.1。另外,在执行这些步骤之前,您需要设置 jre。我使用的是 JDK 11.0.4。
1-右键单击项目的主文件夹-> new-> 目录。
右键单击测试文件夹并创建正确的包。我建议创建与原始类相同的包名称。然后,右键单击 test 目录-> 将目录标记为-> test source root。
3-在 test 目录的右边包中,您需要创建一个 Java 类(我建议使用 Test.Java)。
在创建的类中,输入“@Test”,然后,在 IntelliJ 提供的选项中,选择 Add‘ JUnitx’to classspath。
5-在测试类中编写测试方法。方法签名如下:
@Test
public void test<name of original method>(){
...
}