2016-05-16 36 views
0

如何測試訪問應用程序context的方法,例如爲了從資源中獲取字符串。測試方法包括上下文等

代碼:

public String getString(Context context) { 
    String string = context.getResources().getString(R.id.string); 
    return string; 
} 

測試代碼:

MyClass myClass; 

Context context; // ??? 

@Before 
public void setUp(){ 
    myClass = new MyClass(); 
} 

@Test 
public void convertToMessage() throws Exception { 
    String myString = "My string"; 
    String gettedString = myClass.getString(context); 
    assertEquals(myString, gettedString); 
} 

做什麼用的背景?

回答

2
@Before 
public void setUp(){ 
    myClass = new MyClass(); 
    context = InstrumentationRegistry.getTargetContext(); 
} 

另請參閱the Android testing documentationthe InstrumentationRegistry JavaDocs

+0

事實證明,我應該在設備上運行測試以進行測試? – whalemare

+1

@whalemare:是的,我認爲你正在執行儀器測試。雖然Robolectric或類似的嘲笑框架可能會滿足您的需求,但您沒有可直接用於單元測試的「Context」(即在Android之外進行測試)。 – CommonsWare

+0

好的。感謝您的幫助!) – whalemare