Java – static initializer does not appear to run during JUnit testing

I unit test the method of a static utility class:

@Test
public void createGenreString()
{
    //Arrange
    String expected1 = "Action,Adventure,Animation,//Act
    String actual1 = Utils.createGenreString(new int[]{28,12,16,35});

    //Assert
    assertThat(actual1,is(equalTo(expected1)));
}

This static method is accessing a static map object (moviedbcontract. Genres), which uses integer keys to retrieve string values:

public static String createGenreString(int[] genreIds)
{
    StringBuilder sb = new StringBuilder();
    int length = genreIds.length;
    for (int i = 0; i < length && genreIds[i] != 0; i++)
    {
        if (i != 0) sb.append(",");
        String genre = MovieDbContract.GENRES.get(genreIds[i]);
        sb.append(genre != null ? genre : "UnkNown");
    }
    return sb.toString();
}

This static map object should be populated with data through the static initializer:

public static final SparseArray<String> GENRES = new SparseArray<>();

static
{
    GENRES.put(28,"Action");
    GENRES.put(12,"Adventure");
    GENRES.put(16,"Animation");
    .
    .
}

The problem now is that when the test runs, the map object is null, it does not fill in data, so the test fails But the program itself works normally and contains data Anyone knows why this is different during the test? I'm using JUnit 4.12, which is all done in the Android environment

Solution

Well, it is found that whenever Android framework classes such as SparseArray or contentvalues are used in the tested methods, you must run the test on the simulator or device as an Android test, otherwise these objects will not be initialized as they should be

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>