我以前从未使用过JUnit,我在设置测试时遇到了一些困难。我有一个Java项目和一个包,它们都名为'Project1‘,我正在尝试测试一个类,名为'Module’。目前,我只想检查一下这些值是否正确。
模块类
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");
}
}
}发布于 2014-03-27 17:59:17
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()) ;
}
}发布于 2014-03-27 17:53:10
让Module变量成为测试类中的实例变量,而不是方法中的局部变量。然后,@Before方法将只初始化变量,而不是声明它。然后,它将在任何@Test方法的作用域内。
顺便说一句,==。
发布于 2014-03-27 17:53:57
始终使用等号:
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);
}https://stackoverflow.com/questions/22695408
复制相似问题