运行 单元测试时得到 "Wanted but not invoked"

Getting "Wanted but not invoked" when running unit test

尝试测试存储库方法,但我的测试失败并出现以下“需要但未调用:cellphonesDao.deleteAllCellphones();” 这是回购方法:

@Override
    public Single<Cellphone[]> getCellphones() {
        Single<CellPhoneEntity[]> remoteCellphones =
            networkModule.productApi()
                .getCellPhones()
                .onErrorResumeNext(cellphonesDao.getAllCellphones()); // todo return value if true
        Single<CellPhoneEntity[]> localCellphones = cellphonesDao.getAllCellphones();

        return Single.zip(remoteCellphones, localCellphones, (remote, local) -> {
            if (!Arrays.equals(remote, local)) {
                cellphonesDao.deleteAllCellphones();
                for (CellPhoneEntity cellPhoneEntity : remote) {
                    cellphonesDao.insertCellphone(cellPhoneEntity);
                }
            }

            return mapper.toCellphones(remote);
        });
    }

主要是为了以正确的方式测试 repo 方法。猜猜我选择的方式并不好。 这是测试实现:

class CellPhoneRepositoryImplTest {
    NetworkModule networkModule;
    CellphonesDao cellphonesDao;
    CellphoneMapper cellphoneMapper;
    CellPhoneRepositoryImpl cellPhoneRepository;
    ProductAPI productAPI;

    @BeforeEach
    void setUp() {
        networkModule = Mockito.mock(NetworkModule.class);
        cellphonesDao = Mockito.mock(CellphonesDao.class);
        productAPI = Mockito.mock(ProductAPI.class);
        cellphoneMapper = new CellphoneMapper();
        cellPhoneRepository = Mockito.spy(new CellPhoneRepositoryImpl(
            networkModule,
            cellphonesDao,
            cellphoneMapper
        ));
    }

    @Test
    void whenRemoteDataAreDifferentFromLocalDbIsUpdated() {
        int numberOfCellphones = 5;
        CellPhoneEntity[] remoteCellphones = DummyCellphoneEntityFactory.generateCellphones(numberOfCellphones);
        CellPhoneEntity[] localCellphones = DummyCellphoneEntityFactory.generateCellphones(numberOfCellphones);

        Mockito.when(networkModule.productApi()).thenReturn(productAPI);
        Mockito.when(networkModule.productApi().getCellPhones()).thenReturn(wrapWithSingle(remoteCellphones));
//        Mockito.when(networkModule.productApi().getCellPhones().onErrorResumeNext(cellphonesDao.getAllCellphones())).thenReturn(wrapWithSingle(remoteCellphones));
        Mockito.when(cellphonesDao.getAllCellphones()).thenReturn(wrapWithSingle(localCellphones));

        Mockito.doNothing().when(cellphonesDao).deleteAllCellphones();

        cellPhoneRepository.getCellphones();
        Mockito.verify(cellphonesDao, Mockito.times(1))
            .deleteAllCellphones();
    }

    private Single<CellPhoneEntity[]> wrapWithSingle(CellPhoneEntity[] cellphones) {
        return Single.just(cellphones);
    }
}

我很乐意提出任何建议)

返回的 Single 中的代码不会立即执行,但您的验证会。尝试调用 cellPhoneRepository.getCellphones().blockingGet() 而不是 cellPhoneRepository.getCellphones()blockingGet() 应该让您的测试等到 Single 完成执行。