lundi 25 janvier 2016

How to get Locale from mock context

I'm trying to do some unit testing, and I haven't really settle yet on a runner or test class.

At the end, this is the method I'm verifying it works:

public static void getData(final Context context, final Callback<MyObject> callback) {

    Locale locale = context.getResources().getConfiguration().locale;
    MyObjectService myService = new MyObjectService(getRequestHeaders(context), locale);
}

So I need a mock context that has resources, configuration, locale and SharedPreferences.

I've tried PowerMockito, AndroidTestCase, AndroidTestRunner, ApplicationTestCase. All I can get is a mock Context with nothing in it, or mock Resources, but I can't figure out how to add them to the mock context (basically remake a Context).

This is currently my last attempt (although I've tried more complex ones, without any success):

import com.myApp.android.app.shop.util.ServiceUtils;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.modules.junit4.PowerMockRunner;

import android.content.Context;

@RunWith(PowerMockRunner.class)
public class TestLogin
{
    @Test
    public void test()
    {
        Context context = Mockito.mock(Context.class);
        ServiceUtils.getData(context, dataCallback);
    }
}

The exception I get is a NPE from getData() as the passed context does not have resources.

Any suggestions?

Aucun commentaire:

Enregistrer un commentaire