如何在数据更改时测试 MutableLiveData<>.observe?
How can test MutableLiveData<>.observe when the data is changed?
如果 API 正在使用登录功能,我有下一个测试代码:
@RunWith(RobolectricTestRunner.class)
public class LoginTest {
LoginRespository profileRepository = new LoginRespository(RuntimeEnvironment.application);
@Test
public void testLogin() {
MutableLiveData<ApiResponse<LoginData>> data = new MutableLiveData<>();
String email = "email@email.com";
String password = "email@email.com";
profileRepository.login(data, email, password);
}
}
API return 的数据保存到 data
但我不知道如何将观察者放在这里,因为我需要上下文,也许testLogin
,未完成。
有什么想法吗?
谢谢
最后,我可以用 robolectric 和下一个代码进行测试:
@RunWith(RobolectricTestRunner.class)
public class DownloadProfileTest {
LoginRespository profileRepository = new LoginRespository(RuntimeEnvironment.application);
private ActivityController<LoginActivity> controller;
private LoginActivity activity;
private void createLoginActivityWithIntent() {
activity = controller
.create()
.start()
.get();
}
@Before
public void setUp() {
controller = Robolectric.buildActivity(LoginActivity.class);
}
@Test
public void testUtilsIsValidEmail() {
MutableLiveData<ApiResponse<LoginData>> data = new MutableLiveData<>();
String email = "email@email.com";
String password = "email@email.com";
profileRepository.login(data, email, password);
createLoginActivityWithIntent();
data.observe(activity, (@Nullable ApiResponse<LoginData> loginResponse) -> {
assertTrue(loginResponse != null);
});
}
}
如果 API 正在使用登录功能,我有下一个测试代码:
@RunWith(RobolectricTestRunner.class)
public class LoginTest {
LoginRespository profileRepository = new LoginRespository(RuntimeEnvironment.application);
@Test
public void testLogin() {
MutableLiveData<ApiResponse<LoginData>> data = new MutableLiveData<>();
String email = "email@email.com";
String password = "email@email.com";
profileRepository.login(data, email, password);
}
}
API return 的数据保存到 data
但我不知道如何将观察者放在这里,因为我需要上下文,也许testLogin
,未完成。
有什么想法吗?
谢谢
最后,我可以用 robolectric 和下一个代码进行测试:
@RunWith(RobolectricTestRunner.class)
public class DownloadProfileTest {
LoginRespository profileRepository = new LoginRespository(RuntimeEnvironment.application);
private ActivityController<LoginActivity> controller;
private LoginActivity activity;
private void createLoginActivityWithIntent() {
activity = controller
.create()
.start()
.get();
}
@Before
public void setUp() {
controller = Robolectric.buildActivity(LoginActivity.class);
}
@Test
public void testUtilsIsValidEmail() {
MutableLiveData<ApiResponse<LoginData>> data = new MutableLiveData<>();
String email = "email@email.com";
String password = "email@email.com";
profileRepository.login(data, email, password);
createLoginActivityWithIntent();
data.observe(activity, (@Nullable ApiResponse<LoginData> loginResponse) -> {
assertTrue(loginResponse != null);
});
}
}