2015-12-03 86 views
2

我試圖T選用Robolectricjava.lang.ClassCastException:android.app.Application不能轉換到com.google.android.apps.common.inject.InjectedApplication

@RunWith(RobolectricTestRunner.class) 
@Config(
     manifest = "...mypath.../AndroidManifest.xml", 
     qualifiers = "fr-normal-port-hdpi", 
     sdk = 21, 
     application = Application.class) 
public class SetPaymentActivityTest { 


    @Before 
    public void setUp() throws Exception { 
    } 

    @Test 
    public void sendWrongPaymentDetails() throws Exception { 

     SetPaymentActivity activity = Robolectric.buildActivity(SetPaymentActivity.class) 
//    .attach() 
       .create() 
//    .starst() 
//    .resume() 
//    .visible() 
       .get(); 
     activity = Robolectric.setupActivity(SetPaymentActivity.class); 

//  Shadows.shadowOf(SetPaymentActivity.class); 

     String url = activity.getUrl(); 
     assertThat(url, equalTo("")); 
    } 
} 

PROD代碼:

public class SetPaymentActivity extends FragmentActivity implements DaggerActivity {

,但我得到這個錯誤:

Time: 109.712 
There was 1 failure: 
1) sendWrongPaymentDetails(com.google.android.apps.ridematch.payments.SetPaymentActivityTest) 
java.lang.ClassCastException: android.app.Application cannot be cast to com.google.android.apps.common.inject.InjectedApplication 
    at com.google.android.apps.common.inject.ActivityInjectHelper.initGraph(ActivityInjectHelper.java:56) 

我到底做錯了什麼?

回答

0

也許你需要你的SetPaymentActivityTest來擴展InjectedApplication

這樣的:

public class SetPaymentActivityTest extends InjectedApplication { 
+0

爲什麼我從來沒有在任何例子中看過 –

+0

這只是一個假設。或者可能需要擴展SetPaymentActivity。試試看是否有幫助。 – JFPicard

+0

我無法更改PROD代碼 –

0

這是很容易修復。

更改您的測試代碼到下一個:

@RunWith(RobolectricGradleTestRunner.class) 
@Config(
     constants = BuildConfig.class, 
     qualifiers = "fr-normal-port-hdpi", 
     sdk = 21) 

的問題是,Robolectric試圖爲你的配置,在某些時候你把它投射到您的類

0

我創建了一個指定使用Application虛設TestApplication類:

public TestApplication extends InjectedApplication

和配置:

@Config(
     manifest = "...mypath.../AndroidManifest.xml", 
     qualifiers = "fr-normal-port-hdpi", 
     sdk = 21, 
     application = TestApplication.class) 
相關問題