简体   繁体   English

如何模拟未设置为变量的对象

[英]How to Mock an object that is not set to a variable

I am currently writing unit tests for legacy code. 我目前正在为遗留代码编写单元测试。 I need to Mock an object for a "doReturn" on a function call on that object. 我需要在该对象的函数调用上为“ doReturn”模拟一个对象。 However, that object is instantiated on the same line it is being called and is never assigned to a variable. 但是,该对象在被调用的同一行上实例化,并且从未分配给变量。 Is there a way to mock this return value without touching the original code? 有没有一种方法可以模拟此返回值而不接触原始代码?

Legacy code line containing function call that needs to return a mocked list: 包含函数调用的旧代码行,需要返回一个模拟列表:

List<Map<String, String>> referenceDataList = new ReferenceDataInquiryMapper().execute(referenceDataInquiry);

My attempt at mocking this "execute" call: 我尝试模拟此“执行”调用:

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());

I have also attempted: 我也尝试过:

PowerMockito.doReturn(referenceDataList).when(new ReferenceDataInquiryMapper(),"execute",Mockito.any());

Which throws a PowerMockito error 引发PowerMockito错误

As well as this: 以及:

PowerMockito.doReturn(referenceDataList).when(PowerMockito.mock(ReferenceDataInquiryMapper.class),"execute",Mockito.any());

Which throws the same exception as my first attempt. 这引发了与我的第一次尝试相同的异常。

Instead of returning the Mock value, the first line posted above tries to create an actual new object when the test is ran and throws an exception. 在运行测试并引发异常时,上面发布的第一行尝试返回一个Mock值,而不是返回Mock值。 Is it possible to actually Mock this code? 实际上可以模拟该代码吗?

~Thanks 〜谢谢

when a new object is created, we need to return its mock. 创建新对象时,我们需要返回其模拟。 Add whenNew as below. 如下所示添加whenNew。

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());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM