我当前正在编写旧版代码的单元测试。我需要在该对象上的函数调用上模拟一个" doreturn"对象。但是,该对象是在被调用的同一行上实例化的,并且永远不会分配给变量。有没有办法在不触摸原始代码的情况下模拟此返回值?
旧版代码行包含函数调用,需要返回模拟列表:
List<Map<String, String>> referenceDataList = new ReferenceDataInquiryMapper().execute(referenceDataInquiry);
我尝试嘲笑这个"执行"呼叫:
List<Map<String, String>> referenceDataList = new ArrayList<Map<String, String>>();
//Add data to referenceDataList
ReferenceDataInquiryMapper referenceDataInquiryMapper = PowerMockito.mock(ReferenceDataInquiryMapper.class);
PowerMockito.doReturn(referenceDataList).when(referenceDataInquiryMapper,"execute",Mockito.any());
我也尝试过:
PowerMockito.doReturn(referenceDataList).when(new ReferenceDataInquiryMapper(),"execute",Mockito.any());
抛出PowerMockito错误
以及此:
PowerMockito.doReturn(referenceDataList).when(PowerMockito.mock(ReferenceDataInquiryMapper.class),"execute",Mockito.any());
抛出与我的第一次尝试相同的例外。
而不是返回模拟值,上面发布的第一行试图在测试运行并引发异常时创建一个实际的新对象。是否可以实际模拟此代码?
〜谢谢
创建新对象时,我们需要返回其模拟。添加何时如下。
List<Map<String, String>> referenceDataList = new ArrayList<Map<String, String>>();
//Add data to referenceDataList
ReferenceDataInquiryMapper referenceDataInquiryMapper =
PowerMockito.mock(ReferenceDataInquiryMapper.class);
PowerMockito.whenNew(ReferenceDataInquiryMapper.class).thenReturn( referenceDataInquiryMapper);
PowerMockito.doReturn(referenceDataList).when( referenceDataInquiryMapper,"execute",Mockito.any());