尝试测试方法,但收到“未模拟android.widget.ImageView中的方法setVisibility”

时间:2019-04-02 14:02:41

标签: android junit mocking mockito

我正在尝试测试这种简单的方法,我只想验证一下,如果ViewGroup最终只有1个子视图。

问题是,我的应用程序没有上下文或布局,因此我尝试创建MockContext(),但尝试修改ImageView可见性时仍然遇到相同的错误:“ android.widget中的setVisibility方法。 ImageView未嘲笑” 注意:CloudPearView扩展了ViewGroup

方法(在ViewHandler类中,实现了一个称为IViewHandler的接口)


    public void showAd(AdInfo adInfo) {
        ViewGroup viewGroup = cloudPearView.getViewFromSlot(adInfo.getViewPlace());

        switch(adInfo.getMediaType()){
            case IMAGE:
                DisplayImage(viewGroup,adInfo);
                break;
            case VIDEO:
                DisplayVideo(viewGroup,adInfo);
                break;

        }

    }

    private void DisplayImage(ViewGroup viewGroup, AdInfo adInfo) {
        ImageView newImgView = new ImageView(cloudPearView.getContext());
        newImgView.setVisibility(View.INVISIBLE);

        RelativeLayout.LayoutParams layoutParams = getDisplayType(DISPLAY_TYPE);
        newImgView.setLayoutParams(layoutParams);
        newImgView.setAdjustViewBounds(true);

        newImgView.setImageBitmap(MediaLoader.loadImage(adInfo.getId()));
        viewGroup.removeAllViews();
        newImgView.setVisibility(View.VISIBLE);
        viewGroup.addView(newImgView);

    }

测试:

    @Test
    public void OnCall_ShowAd_DeletesAllOldViewGroupViews() throws PearException.ResourceNotFound {
        // Arrange
        IViewHandler iViewHandler = new ViewHandler();
        CloudPearView cloudPearView = mock(CloudPearView.class);
        AdInfo adInfo = new AdInfo(1550624700L,"images/1534010826237-b53902d7-fb56-455b-827d-cfba0b36e69c.jpg",1,AdInfo.MediaType.IMAGE);
        ViewGroup viewGroup = mock(ViewGroup.class);

        when(cloudPearView.getContext()).thenReturn(new MockContext());
        when(cloudPearView.getViewFromSlot(1)).thenReturn(viewGroup);
        // Act
        iViewHandler.register(cloudPearView);
        iViewHandler.showAd(adInfo);

        // Assert
        verify(viewGroup).removeAllViews();
    }

经过测试,我收到此错误:

java.lang.RuntimeException:android.widget.ImageView中的setVisibility方法没有被模拟。有关详细信息,请参见http://g.co/androidstudio/not-mocked

0 个答案:

没有答案