2017-08-08 59 views
0

創建測試:空指針運行時測試機器人嘲笑

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) 

任何想法,爲什麼?

回答

1

MenuPresenter() - 您不會在代碼中的任何位置調用bindView,因此演示者不知道您的模擬視圖。這意味着它不能只是null

+0

就是這樣!我忘記了在調用方法之前在測試類中添加presenter.bindView(view)。多謝! – edi233