JavaLib
 
Tester
 
Overview
Basic Types
User Types
Inexact Values
Sets
Iterable
Traversals
Maps
Random Choice
Range Check
Equivalence
ISame
Exceptions
Constructors
Methods
CheckFail
 
Sources
Downloads
 
TSRJ Home
TSRJ Local

ISame

The programmer may decide that for one or more classes in his program the equality comparison should be handled in a special way (e.g. only some of the fields have to match, or that Strings should be compared in a case-insensitive manner). In this case these classes should implement the ISame interface by defining the method same that compares this object with the given one. Any two instances of a class that implements the ISame interface will be compared by applying the same method defined in that class. The remainder of the test evaluation follows the regular rules.

The ISame interface is defined as:

// provide a customized comparison of objects in this class
public interface ISame<T>{

  // it this object the same as the given one?
  public boolean same(T that);
}

The following example illustrates the use of the tests that apply user-defined same method:

For the class that represents an Author we define two authors to be same if their last names are the same:

public class Author implements ISame<Author>{
  String lastName;
  String firstName;

  Author(String lastName, String firstName){
    this.lastName = lastName;
    this.firstName = firstName;
  }

  // two authors are same if their last names match
  public boolean same(Author that){
    return this.lastName.equals(that.lastName);
 }
}

We now run the following tests:

// sample books
public Author sk=new Author("King", "Steven");
public Author dk=new Author("King", "Dan");
public Author db=new Author("Brown", "Dan");
  
// sample authors
public Book book1=new Book("title1",sk,4000); 
public Book book2=new Book("title2",db,4000);
public Book book3=new Book("title1",db,4000);
public Book book4=new Book("title1",dk,4000);

void testSame(Tester t){
  t.checkExpect(this.book1, this.book2, 
    "fails: different books, authors");
  t.checkExpect(this.book1, this.book4,  
    "should succeed - same author last names");
  t.checkExpect(this.book3, this.book4 
    "fails: different author last names.");
  t.checkExpect(this.book2, this.book3
    "fails: different titles.");
}

Code sources

Here is the complete source code for this test suite.

You can also download the entire souce code as a zip file.

Complete test results are shown here.


last updated on Mon Apr 4 15:26:25 EDT 2011generated with DrRacket