[英]How to test method that uses system service using Robolectric?
public class SomeClass {
public void someMethod() {
final TelephonyManager telephonyManager = (TelephonyManager)
getContext().getSystemService(Context.TELEPHONY_SERVICE);
..... more code
}
}
我需要測試創建Telephonymanager實例的'someMethod()'。 我的測試代碼如下:
@RunWith(RobolectricTestRunner.class)
@Config(cmanifest = Config.NONE)
public class SomeClassTest {
private TelephonyManager manager;
private ShadowTelephonyManager shadowManager;
@Before
public void setup() {
manager = newInstanceOf(TelephonyManager.class);
shadowManager = shadowOf(manager);
}
@Test
public void testSomeMethod() {
final SomeClass testInstance = new SomeClass();
testInstance.someMethod();
}
}
我在創建電話管理器實例的地方出現了空指針異常。 我嘗試了不同的方法,但沒有任何效果。 有什么建議嗎? 請。
您可以使用@Mock Annotation模擬Telephonymanager API。
假設您的代碼是這樣的:
public class SomeClass {
public void someMethod() {
final TelephonyManager telephonyManager = (TelephonyManager)
getContext().getSystemService(Context.TELEPHONY_SERVICE);
int callState = telephonyManager.getCallState();
}
}
模擬Telephonymanager實際實例的單元測試框架應為:
@RunWith(RobolectricTestRunner.class)
@Config(cmanifest = Config.NONE)
public class SomeClassTest {
@Mock
private TelephonyManager telephonyManager;
@Mock
private Context mContext = ShadowApplication.getInstance().getApplicationContext();
@Before
public void setup() {
initMocks(this);
when(mContext.getSystemService(Context.TELEPHONY_SERVICE)).thenReturn(telephonyManager);
}
@Test
public void testSomeMethod() {
final SomeClass testInstance = new SomeClass();
when(telephonyManager.getCallState()).thenReturn(2);
testInstance.someMethod();
}
}
callState值將是您設置的值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.