我创建了测试:
class MenuPresenterTest {
lateinit var presenter: MenuPresenter
lateinit var view: MenuView
@Before fun setUp() {
view = mock(MenuView::class.java)
presenter = MenuPresenter()
}
@Test fun test_validation() {
presenter.openActivity()
verify(view).openActivity()
}
}
MenuView
interface MenuView : MvpView {
fun init()
fun openActivity()
}
MenuPresenter
@PerActivity
class MenuPresenter @Inject constructor() : MvpPresenter<MenuView>() {
fun initView(){
view.init()
}
fun openActivity(){
view.openActivity()
}
}
MvpPresenter
open class MvpPresenter<V : MvpBaseView> : MvpBasePresenter<V>() {
// things specific for current project
override fun bindView(view: V) {
super.bindView(view)
}
override fun unbindView() {
super.unbindView()
clear()
}
}
MvpBasePresenter:
abstract class MvpBasePresenter<V : MvpBaseView> {
private var viewRef: WeakReference<V>? = null
private val disposables = CompositeDisposable()
fun clear() = disposables.clear()
fun dispose(disposable: Disposable) = disposables.add(disposable)
open fun bindView(view: V) {
viewRef = WeakReference(view)
}
open fun unbindView() {
viewRef = null
}
fun isViewBound() = viewRef != null
val view: V
get() {
if (viewRef == null) {
throw NullPointerException("getView() called when viewRef is null. Ensure bindView(View view) is called first.")
} else {
return viewRef!!.get() as V
}
}
}
当我进行测试时,我得到:
java.lang.NullPointerException: getView() called when viewRef is null. Ensure bindView(View view) is called first.
at base.MvpBasePresenter.getView(MvpBasePresenter.kt:27)
任何想法为什么?
答案 0 :(得分:1)
MenuPresenter()
- 您不会在代码中的任何位置调用bindView
,因此演示者不知道您的模拟视图。这意味着它不能是null
。