我已经编写了48种测试方法来测试课程分配。它们都不是例外测试,但是它们可以正常工作。最后,我尝试测试自己的异常,而jUnit 5则看不到它。我的代码设计和异常测试有一些示例。
import static org.junit.jupiter.api.Assertions.*;
import org.junit.Test;
import junit.framework.TestCase;
public class Final_Tests extends TestCase {
@Test
public static void testD4_setChair() {
Department testD = new Department("CSE 101","CSE 101!");
Teacher testT = new Teacher("Ali","Veli.com",testD,"CV");
testD.setChair(testT);
assertEquals(testT,testD.getChair());
}
测试非异常方法没有问题。问题在这里。
@Test
public static void DepartmentMismatchException_Test() {
Department testD = new Department("CSE 101","CSE 101!");
Teacher testT = new Teacher("Mehmet", "mehmet.com", testD, "CV Mehmet");
Course testC1 = new Course(testD,101,"Test Course 1","Test Course 1 Desc.",testT,6);
String expMsg = "DepartmentMismatchException: Teacher in " + testT.getDepartment().getCode()+ ", Course in " +testC1.getDepartment().getCode();
DepartmentMismatchException dme = new DepartmentMismatchException(testT.getDepartment(), testC1.getDepartment());
assertEquals(expMsg, dme.toString());
}
代码设计是否存在问题,例如使用范围,静态或其他修饰符,或者关于我的异常测试代码?
来自JUnit5
@Test
javadoc:
@Test方法不得为私有或静态,并且不得返回值。
因此,您应该从static
关键字中删除关键字,然后测试应该可以正常运行。
通常,异常会throw
以某种方式测试异常并验证其是否正确thrown
。我看到您正在实例化它,并验证消息是否符合预期,但是最好的方法是:
@Test
public static void DepartmentMismatchException_Test() {
Department testD = new Department("CSE 101","CSE 101!");
Teacher testT = new Teacher("Mehmet", "mehmet.com", testD, "CV Mehmet");
Course testC1 = new Course(testD,101,"Test Course 1","Test Course 1 Desc.",testT,6);
String expMsg = "DepartmentMismatchException: Teacher in " + testT.getDepartment().getCode()+ ", Course in " +testC1.getDepartment().getCode();
Exception thrownException = Assertions.assertThrows(DepartmentMismatchException.class, () -> /* Some code that throws your exception */);
assertEquals(expMsg, thrownException.toString() /* or maybe thrownException.getMessage() */);
}
您可以在此处查看教程和更多示例。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句