我有一个FileRepository
类来填充MutableLiveData。我有两个功能。一种是调用Web服务和设置列表(getAllFilms
(。另一个是用第一个函数 List (getFilmData
( 分配MutableLiveData
。我试着为MutableLiveData
写unit test
.你可以帮我吗?此函数数据始终为空。
public class FilmRepositoryTest
@Mock
FilmRepository frepo;
@Rule
public InstantTaskExecutorRule instantTaskExecutorRule = new InstantTaskExecutorRule();
@Before
public void setUp() throws Exception {
}
@Test
public void getFilmData_forData() throws IOException {
ArrayList<film> filmlistesi = new ArrayList<>();
MutableLiveData<List<film>> bilgi = new MutableLiveData<>();
String arama = "ankara";
filmlistesi.add(new film("Behzat Ç.: Bir Ankara Polisiyesi","2010–2019","tt1795096","series","https://m.media-amazon.com/images/M/MV5BZDZjY2I5ZjEtZGE2MS00ZjRmLTlmMGEtMDQ5ZmZhZWJjYzk3XkEyXkFqcGdeQXVyNDg4MjkzNDk@._V1_SX300.jpg"));
when(frepo.getAllFilms(arama)).thenReturn(filmlistesi);
bilgi.setValue(filmlistesi);
System.out.println(frepo.getFilmData(arama)); // print(NULL)
System.out.println(bilgi.getValue()); // print(filmlistesi)
assertEquals(frepo.getFilmData(arama),bilgi.getValue());
}
public class FilmRepository
public MutableLiveData<List<film>> getFilmData(String a) throws IOException {
MutableLiveData<List<film>> data = new MutableLiveData<>();
data.setValue(getAllFilms(a));
return data;
}
public ArrayList getAllFilms(String filmName) throws IOException {
ArrayList<film> dataset = new ArrayList<>();
return dataset;
}
LiveData或 MutableLiveData 必须有一组Observer
,否则它会返回null
Observer<List<film>> observer = new Observer<List<film>>() {
@Override
public void onChanged(@Nullable List<film> films) {
assertEquals(frepo.getFilmData(arama), films.getValue());
biligi.removeObserver(this)
}
};
bilgi.observeForever(observer);
bilgi.setValue(filmlistesi);