Next page | Contents page |

Exercise 31 - age

Make a simple Person class that includes the following lines.

	private static final long MS_PER_YEAR = 
			(365L * 4 + 1) * 24 * 60 * 60 * 1000 / 4;

	private java.util.Date dateOfBirth;

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

Write the corresponding unit test class. Can you see a problem with testing getAgeInYears() (a problem that will arise for all code that has something in common with this example)?

Work around the problem so the test will always work. Can you ensure 100% line coverage too?

Next page | Contents page |