F0cus
F0cus

Reputation: 625

do a mock on Mocked object in Junit5

I am trying to write a test case in JUNIT5.

I want to do unit test on the below class

Class Service{

@Autowired
ObjectHolder objectHolder;

 UtilityServiceDTOMapper<T> serviceDTOMapper = objectHolder.getImplementation();
 List<Records> recordList = serviceDTOMapper.mapper("Test");//Line I want to do unit test

}

Junit

@Test
void test(){
ReflectionTestUtils.setField(ObjectHolder, "implementations", mock(DTOMapper.class)));
}

//---Now i want to do the unit test for the above line i mentioned.
// I tried like 

when(serviceDTOMapper.mapper(any())).thenReturn(someListOfValues);
//This is not working , getting an empty list not 'someListOfValues'

when(serviceDTOMapper.mapper(any())).thenReturn(someListOfValues);

the above code is what i tried, but its not working.

Upvotes: -1

Views: 152

Answers (1)

Feel free
Feel free

Reputation: 1069

It`s pretty simple to do. You need to call the method which uses your mapper and only then you could mock a behavior of your mock. Test should look like this:

@ExtendWith(MockitoExtension.class)
class ServiceTest {
    @Mock
    private UtilityServiceDTOMapper<String> serviceDTOMapper;

    @InjectMocks
    private Service service;

    @BeforeEach
    void setUp() {
        ReflectionTestUtils.setField(service, "serviceDTOMapper", serviceDTOMapper);
    }

    @Test
    void testMapper() {
        List<Records> someListOfValues = List.of(new Records("test"));

        // Mock the behavior of the mapper method
        when(serviceDTOMapper.mapper(anyString())).thenReturn(someListOfValues);

        // Call the method that uses the mapper
        service.someMethod();

       // Do some verify
       
    }
}

Upvotes: 0

Related Questions