Next page | Contents page |

Age revisited

In an earlier exercise we had

	public int getAgeInYears ()
	{
		long now_ms = new Date ().getTime ();
		long dob_ms = this.dateOfBirth.getTime ();
		return (int) ((now_ms - dob_ms) / MS_PER_YEAR);
	}

The date now is constructed within the method so it cannot be mocked. However the dateOfBirth field can. Construct the Person with a mock Date object, record that it should expect a call to its getTime() method and tell it what to return, as a value with a fixed difference from now. Then the test can use a fixed age as the final int returned from this method.

Next page | Contents page |