如何在用powermockito监视的类中模拟成员

时间:2019-11-01 08:43:14

标签: java spring-boot mockito powermockito

如何模拟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);
    }
}

2 个答案:

答案 0 :(得分:0)

首先,在将BoxFileDao的模拟注入到被测类boxFileService的同时创建您的类。然后,您可以在其上创建间谍。

例如:

BoxFileDao dao = new BoxFileDao();
dao.boxFileService = Mockito.mock(BoxFileService.class);

BoxFileDao spy = Mockito.spy(dao);

但问题是您为什么还要这么做?有理由监视BoxFileDao,即您正在测试的班级吗?

答案 1 :(得分:0)

您可以使用@InjectMock将模拟的boxFileService对象注入实际的boxFileDao对象中。您的测试课程可以写成类似

@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);
    }
}