How can I test this?

时间:2015-11-12 11:19:36

标签: java unit-testing junit

I have this class:

public class EmployeeHours {

    public static final Integer STEP = 60;

    //more fields
    private Integer minutes;

    public void increaseMinutes(){//increase minutes by STEP}

    public void decreaseMinutes(){//decrease minutes by STEP, 0 whether negative}

}

And I want to test it:

    @Test
    public void shouldBeZeroSinceMinutesCantBeNegative() {
        int initialMinutes = 10;
        EmployeeHours employeeHours = new EmployeeHours(null, 1, initialMinutes);
        employeeHours.decreaseMinutes();
        assertThat(employeeHours.getMinutes(), is(0));
    }

This test is passing, beacuse I know that STEP is greater than 10. But if I change STEP to be 5, for instance, it won't pass.

Should I control this situations in the test itself? I mean:

if (STEP > initialMinutes) 
then expectSomething
else expectAnotherThing

Is it a good practice? How can I improve my test?

1 个答案:

答案 0 :(得分:2)

Yes, you should improve your test to be as generic as possible.

Since STEP is a public field, you could initialize your initialMinutes variable to something like STEP - 1. This will correctly test the case where decreasing the minutes ends up in a negative value and it should be set to 0.

@Test
public void shouldBeZeroSinceMinutesCantBeNegative() {
    int initialMinutes = EmployeeHours.STEP - 1;
    EmployeeHours employeeHours = new EmployeeHours(null, 1, initialMinutes);
    employeeHours.decreaseMinutes();
    assertThat(employeeHours.getMinutes(), is(0));
}