2017-07-24 45 views
0

我使用框架的Mockito测试返回一个Observable类(见注释):使用的Mockito,可观察到的地图功能不被称为

这是我的实现类:

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(
    [email protected] 
); 
-> at com.my.package.test.DataRepositoryTest.testGetItem(DataRepositoryTest.java:28) 
Actually, there were zero interactions with this mock. 

我该如何告诉Mockito拨打返回Observablemap()算子/方法,然后apply()

回答

1

看起来不订阅由public Observable<Item> getItem(int id)所以.map(...)运营商不会被调用/返回执行的Observable<Item>,尝试用dataRepository.getItem(anyInt()).subscribe();只是为了验证。