//Service class
MyService extends Service {
private SoundPool mSoundPool;
private int mSoundID;
@Override
public void onCreate(){
mSoundPool = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);
mSoundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() {
@Override
public void onLoadComplete(final SoundPool soundPool, final int sampleId,
final int status) {
mIsSoundLoaded = true;
}
});
//Here I am initializing soundpool and getting resource not found exception
// It should be context of CustomRobolectricTestRunner
mSoundID = mSoundPool.load(getApplicationContext(),R.raw.btn_click, 1);
}
}
//服务测试类获取资源未发现异常使用robolectric
@RunWith(CustomRobolectricTestRunner.class)
//@RunWith(RobolectricTestRunner.class)
public class MyServiceTest
{
@Test
public void testOnCreate()
{
// String hello = this.activity.getString(R.string.app_name);
// assertThat(hello, equalTo("Plus Box"));
MyService service = new MyService();
service.onCreate(); // Getting exception Resource not found.
//To cross check, I have accessed resource in the following way
//and it working fine. I am able to access resource here.
/* int resourceId = Robolectric
.getShadowApplication()
.getResources()
.getIdentifier("btn_click", "raw",
Robolectric.getShadowApplication().getPackageName());
if (resourceId != 0)
{
// Raw folder contains resource.
System.out.println("The value of Raw ID " + resourceId);
assertTrue(true);
}
else
{
// Raw folder doesn't contain resource.
System.out.println("The value of Raw ID " + resourceId);
assertTrue(false);
}
*/
}
}
即使我试图创建自己的自定义测试跑步,因为我的应用程序也有应用类(MyApplication的)。 但似乎,它总是需要MyApplication上下文,而不是TestApplication。 我跟着这个https://groups.google.com/forum/#!topic/robolectric/K2q8xAFfQOA链接。
public class TestApplication extends MyApplication {
@Override
public void onCreate() {
createSession(UserGroup.Unknown, 0, SessionState.Active, "", 0, "");
}
}
public class CustomRobolectricTestRunner extends RobolectricTestRunner
implements TestLifecycle<Application> {
public CustomRobolectricTestRunner(final Class<?> testClass)
throws InitializationError {
super(testClass);
}
@Override
public void afterTest(Method arg0) {
// TODO Auto-generated method stub
}
@Override
public void beforeTest(Method arg0) {
// TODO Auto-generated method stub
}
@Override
public Application createApplication(Method arg0, AndroidManifest manifest) {
TestApplication testApplication = new TestApplication();
ShadowContextWrapper shadowApp = Robolectric.shadowOf(testApplication);
shadowApp.setPackageName("com.example.robolectric");
testApplication.onCreate();
return testApplication;
}
@Override
public void prepareTest(Object arg0) {
// TODO Auto-generated method stub
}
}
任何帮助将非常appreicated。 关注Yuvi
嗨,你错误地解释我的问题。我添加了更多的代码片段。 我不会去测试或模拟来自Android框架的SoudPool相关类。我想做MyService类的单元测试。 – Yuvi