0

我们的老师给了我们一个任务,让我们结合他自己的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;
    }
}

这是 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());
  }

}

现在,构造函数测试通过了,但 setName 和 setSex 没有。他们抛出错误“java.lang.IllegalArgumentException”。我不明白他们为什么不能通过考试。

JUnit 暗示问题是在每个测试开始时创建的“有效”对象(最终 Person 人),并说问题是我抛出了一个非法参数异常,这真的不应该发生。

4

2 回答 2

5
if(sex != 'M' || sex != 'F')

应该

if(sex != 'M' && sex != 'F')
于 2013-02-03T18:21:44.917 回答
0

Person类有一个小问题

    if(sex != 'M' || sex != 'F')

    if(sex != 'M' && sex != 'F')
于 2013-02-03T18:54:30.537 回答