Rancio
Rancio

Reputation: 165

Method call with null date

I'm trying Junit test calls with null date.

Simplified code:

@Test
public void testWithoutDate () {
    WeatherForecast weatherForecast = new WeatherForecast();
    String forecast = weatherForecast.getCityWeather("Madrid", null);
    assertTrue(forecast, true);
}

// Class to test

import java.io.IOException;
import java.util.Calendar;
import java.util.Date;

import org.json.JSONArray;

public class WeatherForecast {

    public String getCityWeather(String city, Date datetime) throws IOException {

        if (datetime == null) {
            datetime = Calendar.getInstance().getTime();
        }

        HttpRequestFactory requestFactory = new NetHttpTransport().createRequestFactory();
        HttpRequest request = requestFactory
            .buildGetRequest(new GenericUrl("https://www.metaweather.com/api/location/search/?query=" + city));
        String rawResponse = request.execute().parseAsString();
        JSONArray jsonArray = new JSONArray(rawResponse);
        return jsonArray.getJSONObject(0).get("woeid").toString();
    }
}

}

I want to call the method dummy with an empty date and if so set that date to today but as expected when I call it from Junit NullPointerException comes to play.

Is there any workaround?

P.S: Sorry for my really bad English skills.

Upvotes: 0

Views: 481

Answers (1)

shubham
shubham

Reputation: 85

This work for me :

WeatherForecast.class

public class WeatherForecast {
  public String getCityWeather(String city, Date date) throws IOException, JSONException 
    {

        if (date == null) {
            date = Calendar.getInstance().getTime();
        }

        HttpRequestFactory requestFactory = new NetHttpTransport().createRequestFactory();
        HttpRequest request = requestFactory
                .buildGetRequest(new GenericUrl("https://www.metaweather.com/api/location/search/?query=" + city));
        String rawResponse = request.execute().parseAsString();
        JSONArray jsonArray = new JSONArray(rawResponse);
        return jsonArray.getJSONObject(0).get("woeid").toString();
    }}

Testcase :

 @Test
public void testWithoutDate () throws IOException, JSONException {
    WeatherForecast weatherForecast = new WeatherForecast();
    String forecast = weatherForecast.getCityWeather("Madrid", null);
    assertTrue(forecast, true);
}

Upvotes: 1

Related Questions