2017-05-08 185 views
0

今天我使用Robolectric,但是我遇到了一些我找不到解決方案的問題。預期結果與實際結果相同,爲什麼它顯示我不同?

MainActivity:

public class MainActivity extends AppCompatActivity { 
private TextView textView; 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     textView=(TextView)findViewById(R.id.textView1); 
     textView.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       Intent intent=new Intent(MainActivity.this,SecondActivity.class); 
       startActivity(intent); 
      } 
     }); 
    } 
} 

MainActivityTest:

@RunWith(RobolectricTestRunner.class) 
@Config(constants = BuildConfig.class,sdk=21) 
public class MainActivityTest { 
    @Test 
    public void testMainActivity() { 
     MainActivity mainActivity = Robolectric.setupActivity(MainActivity.class); 
     mainActivity.findViewById(R.id.textView1).performClick(); 
     Intent expectedIntent = new Intent(mainActivity, SecondActivity.class); 
     ShadowActivity shadowActivity = Shadows.shadowOf(mainActivity); 
     Intent actualIntent = shadowActivity.getNextStartedActivity(); 
     Assert.assertEquals(expectedIntent, actualIntent); 
    } 
} 

錯誤消息:

java.lang.AssertionError: expected: android.content.Intent<Intent { cmp=com.example.wyb.test/.SecondActivity }> but was: android.content.Intent<Intent { cmp=com.example.wyb.test/.SecondActivity }> 
Expected :android.content.Intent<Intent { cmp=com.example.wyb.test/.SecondActivity }> 
Actual :android.content.Intent<Intent { cmp=com.example.wyb.test/.SecondActivity }>  
Process finished with exit code 255 

的build.gradle

apply plugin: 'com.android.application' 

android { 
    compileSdkVersion 25 
    buildToolsVersion "25.0.2" 
    defaultConfig { 
     applicationId "com.example.wyb.test" 
     minSdkVersion 15 
     targetSdkVersion 25 
     versionCode 1 
     versionName "1.0" 
     testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" 
    } 
    buildTypes { 
     release { 
      minifyEnabled false 
      proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 
     } 
    } 
} 

dependencies { 
    testCompile "org.robolectric:robolectric:3.3.2" 

    compile fileTree(dir: 'libs', include: ['*.jar']) 
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', { 
     exclude group: 'com.android.support', module: 'support-annotations' 
    }) 
    compile 'com.android.support:appcompat-v7:25.3.1' 
    compile 'com.android.support.constraint:constraint-layout:1.0.2' 
    testCompile 'junit:junit:4.12' 
} 

我不明白爲什麼預期結果與實際結果相同,但仍然失敗。

回答

0

assertEquals將調用equals方法上比較的對象,但equals不被覆蓋上Intent,所以我認爲它只是在做一個對象引用的比較。

嘗試使用filterEquals來比較意圖。

Assert.assertTrue(actualIntent.filterEquals(expectedIntent)); 

如果filterEquals是不夠的,你(它忽略臨時演員),見this question about comparing intents

+0

它適用於我,謝謝你! –

+0

太好了。不要忘記接受答案。 – GertG

相關問題