gpt4 book ai didi

java - 单元测试android : How to return function not to be null when calls another function return and use

转载 作者:行者123 更新时间:2023-12-02 00:34:52 24 4
gpt4 key购买 nike

我有一个 FileRepository 类来填充 MutableLiveData。我在那里有两个功能。一种是调用 Web 服务并设置列表 (getAllFilms)。另一个是使用第一个函数 List (getFilmData) 分配 MutableLiveData。我尝试为 MutableLiveData 编写单元测试。你能帮助我吗?该函数数据始终为空。

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

关于java - 单元测试android : How to return function not to be null when calls another function return and use,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57987958/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com