mercredi 17 octobre 2018

Cannot get exact number of declared fields in a class, test failed

I have this class:

public class UserPurchaseUtil {
    public static final String JSON_PROP_ID = "id";
    public static final String JSON_PROP_USER_ID = "user_id";
    // See Confluence: First Time Member Promotion (FTM)
    public static final String JSON_PROP_LAST_PURCHASE_TIME = "last_purchase_time";

}

Then, I want to ensure that I pay attention to all the value changes in this class, by "pay attention", I want to ensure that

  • every time I delete or add some constants, a test will fail;
  • all the values are checked.

So I have this test:

@Slf4j
@RunWith(MockitoJUnitRunner.class)
public class UserPurchaseUtilTest {

    @Test
    public void testNumberOfConstantsAndTheirValues() {
        int numberOfConstants = UserPurchaseUtil.class.getDeclaredFields().length;
        // just to ensure we test all the constants' values when we add new ones. Now is 3.
        Assert.assertEquals(3, numberOfConstants);

        Assert.assertEquals("id", UserPurchaseUtil.JSON_PROP_ID);
        Assert.assertEquals("user_id", UserPurchaseUtil.JSON_PROP_USER_ID);
        Assert.assertEquals("last_purchase_time", UserPurchaseUtil.JSON_PROP_LAST_PURCHASE_TIME);
    }
}

But, this simple test fails:

expected:<3> but was:<4>
Expected :3
Actual   :4
 <Click to see difference>

Then, why?





Aucun commentaire:

Enregistrer un commentaire