我使用 hilt 进行依赖注入。
我用这篇文章来进行测试。
https://developer.android.com/training/dependency-injection/hilt-testing
https://dagger.dev/hilt/testing.html
现在想为我的片段编写测试。
我在添加库时遇到问题。
这是我的代码,
这个类是我的跑步者并在 gradle 中使用
class CustomTestRunner : AndroidJUnitRunner() {
override fun newApplication(
cl: ClassLoader?,
className: String?,
context: Context?
): Application {
return super.newApplication(cl, MyCustom_Application::class.java.name, context)
}
}
Run Code Online (Sandbox Code Playgroud)
这是 hilt 生成我在跑步者类中使用的应用程序类的接口
@CustomTestApplication(AndroidApplication::class)
interface MyCustom
Run Code Online (Sandbox Code Playgroud)
这是我的测试课
@HiltAndroidTest
class SettingsActivityTest {
@get:Rule
var hiltRule = HiltAndroidRule(this)
// UI tests here.
@Test
fun test(){
// val activityScenario = launchActivity<MainActivity>()
}
}
Run Code Online (Sandbox Code Playgroud)
我的图书馆
// For instrumented tests.
androidTestImplementation("com.google.dagger:hilt-android-testing:2.28-alpha")
// ...with Kotlin.
kaptAndroidTest("com.google.dagger:hilt-android-compiler:2.34.1-beta")
androidTestImplementation("junit:junit:4.12")
androidTestImplementation ("androidx.test.ext:junit:1.1.2")
androidTestImplementation ("androidx.test.espresso:espresso-core:3.3.0") …Run Code Online (Sandbox Code Playgroud) 我将 Retrofit 与 Rxjava 一起使用来向服务器发出请求。
我的服务器返回定义的 json 格式,其中包括数据和定义的消息。
服务器返回http响应。如果服务器返回成功代码(200)就可以了。
但我希望,如果服务器返回其他代码,我将管理该响应的正文。
例如:
服务器返回401,我想读取响应正文以显示服务器的消息。
但是当服务器其他代码时,改造调用 onError 方法,我无法使用响应正文。
如何解决这个问题?
这是我的方法
'''
private void login(String username , String password){
view.setLoading();
source.loginUser(username, password)
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new SingleObserver<Response<LoginResult>>() {
@Override
public void onSubscribe(Disposable d) {
disposable.add(d);
}
@Override
public void onSuccess(Response<LoginResult> loginResult) {
if (loginResult.isSuccessful()){
}
else
new AlertConfiguration(view.getViewActivity()).showMessage(loginResult.body().getMessage());
}
@Override
public void onError(Throwable e) {
if there is a problem
}
});
Run Code Online (Sandbox Code Playgroud)
'''
这是我改造的接口方法
@POST("...")
Single<Response<LoginResult>> loginUser(@Query("username") String username, @Query("password") String password);
Run Code Online (Sandbox Code Playgroud)