android - 当我用 Kotlin 测试 Retrofit API 时的 NPE
问题描述
我开始学习如何编写测试并编写这个来测试我的api:
class SharedViewModelTest {
@get:Rule
val rule = InstantTaskExecutorRule()
@Mock private lateinit var networkHelper: NetworkHelperImpl
@Mock private lateinit var employeeInteractor: EmployeeInteractorImpl
@Mock private lateinit var specialityInteractor: SpecialityInteractorImpl
@Mock private lateinit var api:ApiService
private lateinit var sharedViewModel: SharedViewModel
@Before fun setUp() {
MockitoAnnotations.initMocks(this)
sharedViewModel = SharedViewModel(networkHelper, employeeInteractor, specialityInteractor)
}
@Test
fun `check is json correct`(){
val result = runBlocking { api.loadData().await().items }
result shouldNotBe null
result.size shouldNotBe 0
}
}
但是当我尝试运行时我有这个check is json correct
:
java.lang.NullPointerException
at com.example.testtask.view.viewmodel.SharedViewModelTest$check is json correct$result$1.invokeSuspend(SharedViewModelTest.kt:38)
at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
at kotlinx.coroutines.DispatchedTask.run(Dispatched.kt:233)
at kotlinx.coroutines.EventLoopImplBase.processNextEvent(EventLoop.kt:116)
at kotlinx.coroutines.BlockingCoroutine.joinBlocking(Builders.kt:76)
at kotlinx.coroutines.BuildersKt__BuildersKt.runBlocking(Builders.kt:53)
at kotlinx.coroutines.BuildersKt.runBlocking(Unknown Source)
at kotlinx.coroutines.BuildersKt__BuildersKt.runBlocking$default(Builders.kt:35)
at kotlinx.coroutines.BuildersKt.runBlocking$default(Unknown Source)
at com.example.testtask.view.viewmodel.SharedViewModelTest.check is json correct(SharedViewModelTest.kt:38)
我真的无法理解为什么我有 NPE(不是线程错误的服务器,NPE exacly)。我评论了我比较结果的行,但它仍然很糟糕,所以我认为这不是关于响应,而是其他的东西。
有人可以向我解释一下吗?
我认为应用程序级别的 gradle 依赖可以提供帮助:
//Tests
testImplementation 'junit:junit:4.13-beta-3'
testImplementation "org.mockito:mockito-inline:2.8.47"
testImplementation 'org.robolectric:robolectric:4.3'
testImplementation 'org.jetbrains.kotlin:kotlin-stdlib:1.3.41'
testImplementation 'org.jetbrains.kotlin:kotlin-test-junit:1.3.41'
testImplementation "com.nhaarman:mockito-kotlin:1.4.0"
testImplementation 'org.amshove.kluent:kluent:1.14'
testImplementation 'android.arch.core:core-testing:1.1.1'
解决方案
您必须先模拟您的 api 响应。例如:
@Test
fun `check is json correct`(){
val result = runBlocking {
whenever(api.loadData()).thenReturn(async {'create your data'})
api.loadData().await().items
}
result shouldNotBe null
result.size shouldNotBe 0
}
推荐阅读
- reactjs - 如何从输入中更新数字
- python - Python 控制 Tcl shell
- javascript - 与 pug 一起使用时,webpack5 不加载 js 和 css 文件路径
- sql-server - 选择所有购买了 ID 为“CENTC”的客户已购买的所有产品的 CustomerNames
- c# - C# - 使用条件编写 ManagementEventWatcher 查询?
- sql - 安装后postgresql错误:与服务器的连接失败
- java - Netbeans JDK上的Glassfish服务器问题不是
- javascript - 查看是否处于严格模式
- directx - d3d11 无法在绘制顺序渲染目标之间更新常量缓冲区
- amazon-cloudformation - CloudFormation 创建初始 SSM 参数,但允许未来从 UI 控制台更新