尝试存根地图时出错

时间:2016-07-29 05:08:47

标签: java unit-testing mockito

我有一种方法,我正在尝试使用模拟进行单元测试。这是方法:

  {...
        mapMasterMap = this.sysAdminService.getMasterData();

        final Map<String, MasterVO> codeMap = (Map<String, MasterVO>) mapMasterMap
                .get("mvo");
        final Map<String, String> sessionMap = (Map<String, String>) mapMasterMap
                .get("smap");
        dataVO.setSessionMap(sessionMap);
        dataVO.setVO1(codeMap.get("vo1"));
        dataVO.setVO2(codeMap.get("vo2"));
        sCommand.setDataVO(dataVO);
    } catch (final Exception e) {
         return mav;
    }
    return mav;
}

我想要做的是将第一行存根,以便mapMasterMap包含一个有效的地图(并且codeMap.gets不会爆炸) - 例如:

{
    @Mock
    private MasterVO masterVO;
        @Mock
    private SysAdminService sysAdminService;


    @InjectMocks
    private SysAdminController sysAdminController;

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
                when(this.sysAdminService.getMasterData())
                .thenReturn(new HashMap<String, MasterVO>() {{
                    this.put("mvo",this.masterVO);
                }};
    }

    @Test
    public final void testType(){}

我收到了一个错误:

  

类型中的方法thenReturn(Map<String,Object>)   OngoingStubbing<Map<String,Object>>不适用于。{   参数(new HashMap<String,MasterVO>(){}

所以,首先 - 我是否遵循正确的方法? 如果是,我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

消息说明了一切:您不能thenReturn HashMap<String, MasterVO> Java请求Map<String,Object>,Mockito来自getMasterData的返回类型。您必须传递HashMap<String, Object>或任何其他Map<String, Object>,这在您的情况下就像更改存根通话中的类型一样简单。

when(this.sysAdminService.getMasterData())
    .thenReturn(new HashMap<String, Object>() {{
        this.put("mvo",this.masterVO);
    }});

为什么?在Java中,generics are not covariant:尽管MasterVO必然会扩展Object,但您无法使用其中一个来代替另一个。否则你可以轻松地做到这一点:

Map<String, MasterVO> stubMap = new HashMap<String, MasterVO>();
when(this.sysAdminService.getMasterData()).thenReturn(stubMap);
Map<String, Object> returnedMap = this.sysAdminService.getMasterData();

// now returnedMap == stubMap, except you've lost some safety
returnedMap.put("and this is why", "generic types are not covariant");  // legal
MasterVO exceptItIsnt = stubMap.get("and this is why");  // ClassCastException!

注意:正如dimo414所提到的,不要使用双括号语法。它会创建一个不必要的Java类,并且可能会泄漏内存。