mardi 24 mai 2016

Android Test - How I could test this function?

I am doing test cases and I don't now how to test this function. Could you give me some ideas? I was trying to use Mockito but I keep getting get null. I would appreciate your help.

This is the function I want to test.

public static Date optDate(JSONObject json, String key) {
    if(!json.isNull(key)) {
        try {
            DateTime dt = JSONUtils.dateFormatter.withZoneUTC().parseDateTime(json.optString(key));
            Date date = dt.toDate();
            return date;
        } catch(Exception e) {
        }
    }
    return null;
}

And I am testing it in this way.

    @RunWith(MockitoJUnitRunner.class)
public class JSONUtilsTest {
    static String dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
    static DateTimeFormatter dateFormatter = DateTimeFormat.forPattern(dateFormat);
    DateTime dt = JSONUtilsTest.dateFormatter.withZoneUTC().parseDateTime("2011-11-02T02:50:12.208Z");
    Date date = dt.toDate();

    @Mock
    JSONObject JSONMock = Mockito.mock(JSONObject.class);
    JSONUtils mJSONUtils = Mockito.mock(JSONUtils.class);


    @Before
    public void setup() {
        doReturn(date).when(mJSONUtils).optDate(JSONMock,"possessionDate");
    }


    @Test
    public void optDateShouldReturnValueOnValidString() {
            Date result = JSONUtils.optDate(JSONMock, "possessionDate");
            Assert.assertEquals("2011-11-02",result);

    }


}

Aucun commentaire:

Enregistrer un commentaire