我们的老师给了我们一个与他自己的junit测试课一起编写一个非常简单的程序的任务.我已经这样做了,但我不太明白我是否得到了正确的结果,或者是否整个事情都被打破了.
这是我们正在测试的类(我写的那个):
package person;
public class Person {
private String name;
private char sex;
public Person(String name, char sex) {
if(name == null || name.equals(""))
throw new IllegalArgumentException();
if(sex != 'M' || sex != 'F')
throw new IllegalArgumentException();
this.name = name;
this.sex = sex;
}
public void setName(String name) {
if(name == null || name.equals(""))
throw new IllegalArgumentException();
this.name = name;
}
public void setSex(char sex) {
if(sex != 'M' || sex != 'F')
throw new IllegalArgumentException();
this.sex = sex;
}
public String getName() {
return name;
}
public char getSex() {
return sex;
}
}
Run Code Online (Sandbox Code Playgroud)
这是JUnit测试类:
package parameterchecking;
import person.Person;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author andersb
*/
public class PersonTest2 {
@Test
public void constructor() {
try {
new Person(null, 'F');
fail("Should throw exception");
} catch (IllegalArgumentException ex) { /* expected */ }
try {
new Person("", 'F');
fail("Should throw exception");
} catch (IllegalArgumentException ex) { /* expected */ }
try {
new Person("Anders", 'W');
fail("Should throw exception");
} catch (IllegalArgumentException ex) { /* expected */ }
}
@Test
public void setSex() {
final Person person = new Person("SomeName", 'M');
try {
person.setSex('L');
fail("Should throw exception");
} catch (IllegalArgumentException ex) { /* expected */ }
person.setSex('F');
assertSame('F', person.getSex());
}
@Test
public void setName() {
final Person person = new Person("Anders", 'M');
try {
person.setName(null);
fail("Should throw exception");
} catch (IllegalArgumentException ex) { /* expected */ }
try {
person.setName("");
fail("Should throw exception");
} catch (IllegalArgumentException ex) { /* expected */ }
person.setName("Henrik");
assertEquals("Henrik", person.getName());
}
}
Run Code Online (Sandbox Code Playgroud)
现在,构造函数测试通过,但setName和setSex没有.他们抛出一个错误"java.lang.IllegalArgumentException".我不明白他们为什么不通过考试.
JUnit暗示问题是在每个测试开始时创建"有效"对象(最终Person人员),并且说问题是我抛出了一个非法的参数异常,这真的不应该发生.
if(sex != 'M' || sex != 'F')
Run Code Online (Sandbox Code Playgroud)
应该
if(sex != 'M' && sex != 'F')
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
320 次 |
| 最近记录: |