如何在测试类中正确设置mockito?

时间:2017-06-05 10:55:07

标签: android unit-testing junit mockito firebase-cloud-messaging

我使用Mockito编写了测试handleFirebaseMessagesBigText()handleFirebaseMessagesBigPicture()。    在@Before下,在函数init()中,如果我没有注释掉最后两行,那么这两个测试和我的所有其他测试也会因某些原因而失败。如果我注释掉这2行,则上面的2个测试失败。我无法使这些测试工作。我该如何解决?

@RunWith(AndroidJUnit4.class)
public class MainActivityTest {

    private Context context;

    @Mock
    private HandleFirebaseMessages handleFirebaseMessages;

    @Rule
    public ActivityTestRule<MainActivity> activityTestRule =
            new ActivityTestRule<>(MainActivity.class);

    @Before
    public void init() {
        context = InstrumentationRegistry.getTargetContext();
        //MockitoAnnotations.initMocks(this);
        //handleFirebaseMessages = new HandleFirebaseMessages();
    }

 @Test
    public void handleFirebaseMessagesBigText() {
        RemoteMessage remoteMessage = new RemoteMessage.Builder("token").addData("type","1").build();
        handleFirebaseMessages.onMessageReceived(remoteMessage);
        Map<String,String> data = new HashMap<>() ;
        data.put("type","1");
        Mockito.verify(handleFirebaseMessages).buildNotificationBigText(data);
    }

    @Test
    public void handleFirebaseMessagesBigPicture() {
        RemoteMessage remoteMessage = new RemoteMessage.Builder("token").addData("type","2").build();
        handleFirebaseMessages.onMessageReceived(remoteMessage);
        Map<String,String> data = new HashMap<>() ;
        data.put("type","2");
                 Mockito.verify(handleFirebaseMessages).buildNotificationBigPicture(data);
    }
}

修改 我的两个测试方法都出现以下错误:

  java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference

正如您在代码中看到的那样,我将测试函数中的键值对“type” - “1”传递给onMessageReceived()。然后我得到这两个错误。      但是,如果我使用firebase控制台发送具有此确切键值对的消息,则一切正常。所以我猜我使用RemoteMessage将密钥值对发送到onMessageReceived()的方式有问题。

1 个答案:

答案 0 :(得分:0)

您已经使用handleFirebaseMessages注释模拟了实例变量@Mock,因此您无需自己创建实例(Mockito会)。

试试这个:

@Before
public void init() {
    context = InstrumentationRegistry.getTargetContext();
    MockitoAnnotations.initMocks(this);
    //handleFirebaseMessages = new HandleFirebaseMessages();
}