Unit testing on Android Studio: “not mocked” error

前端 未结 2 603
伪装坚强ぢ
伪装坚强ぢ 2021-02-13 09:17

I am new to Android Studio. I am using Android Studio 1.2 preview 2, gradle 2.2.1 and gradle plugin 1.1.0.

I cannot get around this error, when trying to run my unit te

2条回答
  •  难免孤独
    2021-02-13 09:42

    I see you have updated your question.

    Please take a look at the source of this SharedPreferencesMockContext.java: https://github.com/applicake/Beandroid/blob/master/Beanstalk%20Android%20ClientTest/src/com/applicake/beanstalkclient/test/SharedPreferencesMockContext.java.

    Here is the test: https://github.com/applicake/Beandroid/blob/master/Beanstalk%20Android%20ClientTest/src/com/applicake/beanstalkclient/test/NotificationsTests.java

    Here is a snippet show how they created their Mock:

      @Override
      protected void setUp() throws Exception {
    
        final SharedPreferencesMockContext mockContext = new SharedPreferencesMockContext(getContext());
        MockApplication mockApplication = new MockApplication(){
          @Override
          public Context getApplicationContext() {
            Log.d("tests", "Im here");
            return mockContext;
          }
        };
    
    
        context = mockContext;
        setApplication(mockApplication);
        prefs = PreferenceManager.getDefaultSharedPreferences(context);
        prefs.edit().clear().commit();
    
        super.setUp();
      }
    

    I ran into this error last night. Try using "MockContext".

    public class AppPreferencesTest extends InstrumentationTestCase {
    
    AppPreferences preferences;
    Context context;
    
    @Before
    public void setUp() throws Exception {
        context = new MockContext();
        preferences = new AppPreferences(context);
    }
    

    Please see other examples here: https://stackoverflow.com/a/29063736/950427

提交回复
热议问题