2017-09-28 67 views
1

我想验证特定的演员是否添加到意图,但所有的时间,我在单元测试Android意图为空。我有以下的类需要被测试:单元测试中的意图演示Android Mockito

public class TestClass extends SomeNotifier { 
     private Intent mIntent = new Intent("testintent"); 

     public TestClassConstructor(Context context) { 
      super(context); 
     } 

     @Override 
     public void notifyChange() { 
      mIntent.putExtra("Key one", 22); 
      mIntent.putExtra("Key two", 23); 
      mIntent.putExtra("Key three", 24); 
      getContext().sendBroadcast(mIntent); 
     } 
    } 

并且测试下(我mockIntent尝试为好,但结果是一样的,再额外为null):

@RunWith(MockitoJUnitRunner.class) 
public class TestClassTest { 

    @Mock 
    Context mMockContext; 

    @Test 
    public void sendBroadcastTest() { 

    ArgumentCaptor<Intent> argument = ArgumentCaptor.forClass(Intent.class); 

    TestClass testClassNotifier = new TestClass (mMockContext); 
    testClassNotifier.notifyChange(); 
    verify(mMockContext).sendBroadcast(argument.capture()); 


Intent intent = argument.getValue(); 
//THE INTENT IS NULL 
Assert.assertTrue(intent.hasExtra("Key one")); 

    } 
} 

你有什么建议我应该如何使这个测试工作? 在此先感谢

回答

0

Intent和其他Android运行时类(如Context)默认情况下仅在物理Android手机和仿真器上可用。对于本地单元测试,您将获得运行时的残缺版本,默认情况下,Intent等方法将返回null。有关说明,请参阅this question

这意味着您当前的测试正在针对Intent的残缺版本进行验证,默认情况下将针对所有方法调用返回null

有一些解决方法 - 您可以将测试转换为仪器化的单元测试,这意味着您必须在真正的手机或模拟器上运行测试。或者,您可以用您控制的类包装Intent类。

也许最好的解决方案是使用像Robolectric这样的框架。这将为您提供在您的IDE中运行的本地单元测试的重要Android类(如Intent)的工作测试双打(称为阴影)。

一旦你仔细安装Robolectric则只需添加以下,使您的测试工作:

@RunWith(RobolectricTestrunner.class) 
public class TestClassTest { 

顺便说一句,请确保您使用的是Android上进行的Mockito正确的依赖关系:

testCompile 'org.mockito:mockito-core:2.8.9' 
androidTestCompile 'org.mockito:mockito-android:2.8.9' 
相关问题