我的视图模型持有一个非常简单的recyclerview适配器。
当我尝试发送消息(自然地调用notifyDatasetChanged
),它会抛出以下异常:
java.lang.NullPointerException
at androidx.recyclerview.widget.RecyclerView$AdapterDataObservable.notifyChanged(RecyclerView.java:11996)
at
问题在于来自AdapterDataObservable的mObservers变量为空。问题出在这个类扩展了Observable,而这个类又将mObservers定义为。
protected final ArrayList<T> mObservers = new ArrayList<T>();
基本上,一旦我的适配器被实例化,它就会调用
(Tip: The original sentence is already concise and easy to understand, so it just needs to be translated into Chinese without changing the meaning.)private final AdapterDataObservable mObservable = new AdapterDataObservable();
(顺便说一下,这被称为mObservable不为空)
它应该调用mObservers = new ArrayList<T>();
有人能解释为什么这从来没有被调用吗?或者是否有方法可以解决这个问题?
另外,适配器没有被模拟,它是一个实体对象。
编辑:
这里是我使用的测试代码:
class LoginViewModelTest {
private lateinit var vm: LoginViewModel
@get:Rule
val rule = InstantTaskExecutorRule()
@Before
fun setUp() {
whenever(settings.hasShownWelcome).thenReturn(false)
whenever(settings.serverIp).thenReturn("http://127.0.0.1")
//this is where the crash happens
vm = LoginViewModel(settings, service, app, TestLog, TestDispatchers) { p -> permissionGranted }
}
以下是被测试的代码:
class LoginViewModel(private val settings: ISettings, private val service: AppService, application: Application, l: ILog, dispatchers: IDispatchers, val permissionChecker: (String) -> Boolean) : BaseViewModel(application, l, dispatchers)
val stepAdapter :StepAdapter
init {
val maxSteps = calculateSteps()
//after this assignment, during the normal run, the stepAdapter.mObservable.mObservers is an empty array
//during unit tests, after this assignment it is null
stepAdapter = StepAdapter(maxSteps)
}