Search code examples
javaspring-bootmockitopowermockito

How to mock a member in the Class that you spy with powermockito


How can I mock a member class in another class which has already been spied by PowerMockito.spy()?

@Component
public class BoxFileDao {

    @Autowired
    private BoxFileService boxFileService;

    public void uploadFile() {
         .....
         boxFileService.uploadFile(user, credential);
    }
}

@RunWith(PowerMockRunner.class)
@PrepareForTest(BoxFileDao.class)
public class BoxFileDaoTest {
    @Test
    public void testUploadFile() {
        BoxFileDao mock = PowerMockito.spy(new BoxFileDao());
        (how do I get the boxFileService from mock?)
        mock.uploadFile();
        verify(boxFileService).uploadFile(user, credential);
    }
}

Solution

  • You can use @InjectMock to inject the mocked boxFileService object in the real boxFileDao object. Your test class can be written something like

    @RunWith(PowerMockRunner.class)
    public class BoxFileDaoTest {
    
        @Mock
        private BoxFileService boxFileService;
    
        @InjectMocks
        private BoxFileDao boxFileDao;
    
        @Test
        public void testUploadFile() {
            boxFileDao.uploadFile();
            verify(boxFileService).uploadFile(user, credential);
        }
    }