【发布时间】:2025-12-31 14:35:10
【问题描述】:
我的问题是:如果我有一个测试方法,让我们说一个代表一个人的对象的构造函数:
public void Person(String name){this.name = name;},创建一个测试用例是不是很傻:
public class PersonTest {
@Test
public void testPerson() throws myException{
// First thing I want to test
try {
new Person("name to looooooooooooooong");
fail("This test was supposed to throw an exception: name too long");
} catch (Exception e) {
if (e instanceof myException)
assertEquals("MSG: name not valid!", "Name not valid", e.getMessage());
}
//Second thing I want to test
try {
new Person("name to short");
fail("This test was supposed to throw an exception: name too short");
} catch (Exception e) {
if (e instanceof myException)
assertEquals("MSG: name not valid!", "Name not valid", e.getMessage());
}
//Oter things I want to test ...
}
或者我应该为每个对象创建一个测试套件,并为每个要测试的方法创建一个测试用例?但是如果我想测试一个方法的多个参数怎么办?我应该为每个案例编写一个测试用例吗?喜欢:
- 一个名称太长的测试用例
- 一个名称太短的测试用例
- 一个包含数字名称的测试用例 等等?
【问题讨论】:
-
最佳实践是为关于生产代码行为的每一个假设编写一个测试用例。除此之外:检查构造函数中名称的长度等业务规则可能为时已晚......
标签: java unit-testing testing junit