使用Mockito,不会调用Observable的map函数

时间:2017-07-24 23:16:17

标签: android mockito observable

我正在使用Mockito框架来测试返回Observable的类(请参阅注释):

这是我的实现类:

public class DataRepository implements AbstractRepository {

    private DataSource dataSource;
    private DataMapper dataMapper;

    // Constructor
    public DataRepository(DataSource dataSource, DataMapper dataMapper) {
        this.dataSource = dataSource;
        this.dataMapper = dataMapper;
    }

    /**
    * The call to dataSource.getItem(int) returns
    * an Observable of type ItemResponse.
    * So, in the map I cast it to an object of type Item.
    **/
    public Observable<Item> getItem(int id) {
        return dataSource.getItem(id)
            .map(new Function<ItemResponse, Item>() {
                @Override
                public Item apply(ItemResponse itemResponse) throws Exception {
                    return dataMapper.transform(itemResponse);
                }
            });

    }
}

现在,这是我的测试类:

@RunWith(MockitoJUnitRunner.class)
public class DataRepositoryTest {

    DataRepository dataRepository;

    @Mock
    DataSource dataSource;

    @Mock
    DataMapper dataMapper;

    @Before
    public void setUp() {
        dataRepository = new DataRepository(dataSource, dataMapper);
    }

    @Test
    public void testGetItem() {
        // Given
        ItemResponse itemResponse = new ItemResponse();    
        given(dataSource.getItem(anyInt())).willReturn(Observable.just(itemResponse));

        // When
        dataRepository.getItem(anyInt());

        // Verify/then
        verify(dataSource).getItem(anyInt()); // This part runs fine.
        verify(dataMapper).transform(); // This is failing

    }

}

我收到的错误消息是:

Wanted but not invoked:
dataMapper.transform(
    com.my.package.ItemResponse@e720b71
);
-> at com.my.package.test.DataRepositoryTest.testGetItem(DataRepositoryTest.java:28)
Actually, there were zero interactions with this mock.

如何告诉Mockito调用map()运算符/方法,然后调用apply()返回的Observable的{​​{1}}?

1 个答案:

答案 0 :(得分:1)

您似乎没有订阅Observable<Item>返回的public Observable<Item> getItem(int id),因此.map(...)运算符未被调用/执行,请尝试使用dataRepository.getItem(anyInt()).subscribe();进行验证。