[英]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
}
}
I need to test 'someMethod()' which creates instance of telephonymanager. 我需要测试创建Telephonymanager实例的'someMethod()'。 My test code is as below: 我的测试代码如下:
@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();
}
}
I am getting Null pointer exception where telephony manager instance is being created. 我在创建电话管理器实例的地方出现了空指针异常。 I tried different ways but none has worked. 我尝试了不同的方法,但没有任何效果。 Any suggestion ? 有什么建议吗? Please. 请。
You can mock the Telephonymanager API's using @Mock Annotation. 您可以使用@Mock Annotation模拟Telephonymanager API。
Suppose your code is something like this: 假设您的代码是这样的:
public class SomeClass {
public void someMethod() {
final TelephonyManager telephonyManager = (TelephonyManager)
getContext().getSystemService(Context.TELEPHONY_SERVICE);
int callState = telephonyManager.getCallState();
}
}
Your Unit Test framework to mock the actual instance of telephonymanager should be: 模拟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();
}
}
The callState value will be the value what you set. callState值将是您设置的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.