2017-05-22 64 views

回答

-1

下面的例子是谷歌教程

它顯示瞭如何創建一個使用一個模擬的Context對象單元測試。

要使用這個框架模擬對象添加到您當地的單元測試,遵循這種編程模型:

import static org.hamcrest.MatcherAssert.assertThat; 
import static org.hamcrest.CoreMatchers.*; 
import static org.mockito.Mockito.*; 
import org.junit.Test; 
import org.junit.runner.RunWith; 
import org.mockito.Mock; 
import org.mockito.runners.MockitoJUnitRunner; 
import android.content.SharedPreferences; 

@RunWith(MockitoJUnitRunner.class) 
public class UnitTestSample { 

    private static final String FAKE_STRING = "HELLO WORLD"; 

    @Mock 
    Context mMockContext; 

    @Test 
    public void readStringFromContext_LocalizedString() { 
     // Given a mocked Context injected into the object under test... 
     when(mMockContext.getString(R.string.hello_word)) 
       .thenReturn(FAKE_STRING); 
     ClassUnderTest myObjectUnderTest = new ClassUnderTest(mMockContext); 

     // ...when the string is returned from the object under test... 
     String result = myObjectUnderTest.getHelloWorldString(); 

     // ...then the result should be the expected one. 
     assertThat(result, is(FAKE_STRING)); 
    } 
} 

Building Local Unit Tests

+0

我想初始化一個領域實例,所以我不能使用的嘲笑上下文 –