简体   繁体   中英

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. 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

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. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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