public class SomeClass {
public void someMethod() {
final TelephonyManager telephonyManager = (TelephonyManager)
getContext().getSystemService(Context.TELEPHONY_SERVICE);
..... more code
}
}
我需要测试一些方法()'它创建了电话管理器的实例。我的测试代码如下:
@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();
}
}
我正在创建电话管理器实例的Null指针异常。我试过不同的方法,但没有一个有效。有什么建议吗?请。
答案 0 :(得分:0)
您可以使用@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值将是您设置的值。