我以前从未使用过JUnit,并且在设置测试时遇到了一些麻烦。我有一个Java项目和一个包,都命名为"Project1",其中有一个类,我试图测试称为"模块"。现在我只是想检查一下这些值是否正确。
<<p> 模块类/strong>package Project1;
//This class represents a module
public class Module {
public final static int MSC_MODULE_PASS_MARK = 50;
public final static int UG_MODULE_PASS_MARK = 40;
public final static int MSC_MODULE_LEVEL = 7;
public final static int STAGE_3_MODULE_LEVEL = 6;
private String moduleCode;
private String moduleTitle;
private int sem1Credits;
private int sem2Credits;
private int sem3Credits;
private int moduleLevel;
public Module(String code, String title, int sem1, int sem2, int sem3, int level)
{
moduleCode = code;
moduleTitle = title;
sem1Credits = sem1;
sem2Credits = sem2;
sem3Credits = sem3;
moduleLevel = level;
}
//method to return the module code
public String getCode()
{
return moduleCode;
}
//INSERT A BUNCH OF GET METHODS
}
测试用例这就是我迷路的地方。我试图给出一些虚拟值来测试,但我不确定如何通过模块的实例来测试。
package Project1;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
public class TestCase {
@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
@Before
public void setUp() throws Exception {
Module csc8001 = new Module("CSC8001", "Programming and data structures", 20, 0, 0, 7);
}
@Test
public void test() {
if (csc8001.getCode() == "CSC8001") {
System.out.println("Correct");
}
else{
fail("Not yet implemented");
}
}
}
使您的Module
变量成为测试类中的实例变量,而不是方法中的局部变量。然后@Before
方法将初始化变量,而不是声明它。然后,它将在任何@Test
方法的范围内。
顺便说一下,将您的字符串内容与String
的equals
方法进行比较,而不是==
。
import static org.junit.Assert.assertEquals;
public class TestCase {
private final Module csc8001 = new Module("CSC8001", "Programming and data structures", 20, 0, 0, 7);
@Test
public void testGetCode() {
assertEquals("Some error message", "CSC8001", csc8001.getCode()) ;
}
}
始终使用equals:
if (csc8001.getCode().equals("CSC8001")) {
进一步声明csc8001为类成员。
public class TestCase {
private Module csc8001;
和
@Before
public void setUp() throws Exception {
csc8001 = new Module("CSC8001", "Programming and data structures", 20, 0, 0, 7);
}
将Module
设置为实例变量。请记住,对于每个单独的@Test
方法,JUnit将创建测试类的单独实例,并在其上运行所有@Before
方法。尽管您可以在声明系统的相同位置实例化被测系统,但将它保留在@Before
中可能是有利的。
public class TestCase {
private Module csc8001;
@Before public void setUp() throws Exception {
csc8001 = new Module("CSC8001", "Programming and data structures", 20, 0, 0, 7);
}
@Test public void test() { /* ... */ }
}
您也可以使用assertEquals
来检查相等性,如果参数不匹配,它将自动用明确的消息fail
。
@Test
public void codeShouldEqualCSC8001() {
assertEquals("CSC8001", csc8001.getCode());
}
参见assertEquals
和更多内容,请参阅org.junit.Assert文档。
注。请记住,前缀test
和名称setUp
是junit3的保留,使用JUnit4或更好的版本(带有@Before
和@Test
之类的注释),您可以自由地添加多个@Before
和@After
方法,并为所有方法提供不受约束的名称。