The Contract for Equality[java]

As we Know,The Java API documentation for the equals method in Object provides a list of what defines an equivalence relation between two objects:

Reflexivity:
x.equals(x)

Symmetry:
x.equals(y) if-and-only-if (iff) y.equals(x)

Transitivity:
if x.equals(y) and y.equals(z), then x.equals(z)

Consistency:
x.equals(y) returns a consistent value given consistent state

Comparison to null:
!x.equals(null)



let's look a simple example,the test code:
import junit.framework.TestCase;

public class CourseTest extends TestCase {
	public void testCreate() {
		Course course = new Course("CMSC", "120");
		assertEquals("CMSC", course.getDepartment());
		assertEquals("120", course.getNumber());
	}

	public void testEquality() {
		Course courseA = new Course("NURS", "201");
		Course courseAPrime = new Course("NURS", "201");
		assertEquals(courseA, courseAPrime);

		Course courseB = new Course("ARTH", "330");
		assertFalse(courseA.equals(courseB));

		// reflexivity
		assertEquals(courseA, courseA);

		// transitivity
		Course courseAPrime2 = new Course("NURS", "201");
		assertEquals(courseAPrime, courseAPrime2);
		assertEquals(courseA, courseAPrime2);

		// symmetry
		assertEquals(courseAPrime, courseA);

		// consistency
		assertEquals(courseA, courseAPrime);

		// comparison to null
		assertFalse(courseA.equals(null));
		
		assertFalse(courseA.equals("CMSC-120"));
	}
}



the class is:
public class Course {

	private String department;

	private String number;

	public Course(String department, String number) {
		this.department = department;
		this.number = number;
	}

	public String getDepartment() {
		return department;
	}

	public String getNumber() {
		return number;
	}

	@Override
	public boolean equals(Object object) {
		if (object == null)
			return false;
		if (!(object instanceof Course))
			return false;
		Course that = (Course) object;
		return this.department.equals(that.department)
				&& this.number.equals(that.number);

	}
}

see about:<<agile java>> Lession 9,The Contract for Equality

你可能感兴趣的:(java,JUnit)