dimanche 5 janvier 2020

NullPointerException while setting field in Test Class

I'm getting a NullPointerException while trying to set a variable using Reflection in a Test class.

Cities.java initializes filename from application.properties using @Value annotation CitiesTest.java is supposed to initialize filename through Reflection, instead I get a NPE.

What am I doing wrong ?

Cities.java

@Component
public class Cities
{
    private final List<City> cities;
    @Value("${filename.Cities}")
    private String filename;

    public Cities(Gson gson)
    {
        this.gson   = gson;
        this.cities = generateCities();
    }

    private List<City> generateCities()
    {
        List<City> cities = new ArrayList<>();
        try (
                Reader reader = new InputStreamReader(Cities.class.getResourceAsStream("/" + filename))
        )
        {
            Type listType = new TypeToken<ArrayList<City>>() {}.getType();
            cities = gson.fromJson(reader, listType);
        }
        catch (IOException e)
        {
            logger.severe("Failed to read file. Error: " + e);
        }
        return cities;
    }
}

CitiesTest.java

@TestPropertySource(properties = {"filename.Cities=cities.json"})
class CitiesTest
{
    Cities cities;

    @BeforeEach
    public void setUp()
    {
        cities = new Cities(new Gson());
        setField(cities, "filename", "cities.json");
    }

    @Test
    void isCityTest2()
    {
        assertFalse(cities.isCity("USA"), "City not found in localDbase");
    }

}




Aucun commentaire:

Enregistrer un commentaire