模拟方法出错

我试图嘲笑项目中的一些方法,以便在被调用时返回一定的值。 但是当你运行测试时,它们会随输出而下降:

org.mockito.exceptions.misusing.InvalidUseOfMatchersException:使用参数匹配器无效! 0 matchers expected,1 recorded: – > at com.hodzi.stackviewer.questions.detail.QuestionDetailPresenterTest.voteTest(QuestionDetailPresenterTest.kt:69)

如果匹配器与原始值结合,则可能发生此异常://不正确:someMethod(anyObject(),“raw String”); 在使用匹配器时,所有参数都必须由匹配器提供。 例如:// correct:someMethod(anyObject(),eq(“String by matcher”));

如果在调试模式下运行相同的代码并遍历所有行,那么当调用shared.getToken()时,将返回指定的值。 但是正常的启动,测试落在这条线上。

码:

import com.hodzi.stackviewer.questions.QuestionsInteractor import com.hodzi.stackviewer.utils.Shared import com.hodzi.stackviewer.utils.Vote import org.junit.BeforeClass import org.junit.Test import org.mockito.ArgumentMatchers import org.mockito.Mockito internal class QuestionDetailPresenterTest { companion object { lateinit var presenter: QuestionDetailPresenter lateinit var view: QuestionDetailView @BeforeClass @JvmStatic fun setUp() { val questionsInteractor: QuestionsInteractor = Mockito.mock(QuestionsInteractor::class.java) val shared: Shared = Mockito.mock(Shared::class.java) Mockito.`when`(shared.getToken()).thenReturn("23") // Mockito.doReturn("23").`when`(shared).getToken() view = Mockito.mock(QuestionDetailView::class.java) presenter = QuestionDetailPresenter(questionsInteractor, shared) } } @Test fun voteTest() { presenter.vote(ArgumentMatchers.anyInt(), Vote.QUESTION_DOWN) Mockito.verify(view).goToAuth() } } 

共享:

 interface Shared { companion object { const val KEY_TOKEN: String = "keyToken" } fun getToken(): String fun saveToken(token: String?) } 

主持人:

 class QuestionDetailPresenter(val questionsInteractor: QuestionsInteractor, val shared: Shared) : BasePresenter<QuestionDetailView>() { lateinit var question: Question fun vote(id: Int, vote: Vote) { print(vote) if (Strings.isEmptyString(shared.getToken())) { view?.goToAuth() return } val observable: Observable<out Data> = when (vote) { Vote.ANSWER_UP -> { questionsInteractor.answerUpVote(id, shared.getToken()) } Vote.ANSWER_DOWN -> { questionsInteractor.answerDownVote(id, shared.getToken()) } Vote.QUESTION_UP -> { questionsInteractor.questionUpVote(id, shared.getToken()) } Vote.QUESTION_DOWN -> { questionsInteractor.questionDownVote(id, shared.getToken()) } } baseObservableData(observable, { data -> run { Log.d(Const.LOG_TAG, "success") } }, { throwable -> run { Log.d(Const.LOG_TAG, "error") } } ) } } 

谢谢!

嘲笑shared没有什么不妥,我认为问题在于:

  presenter.vote(ArgumentMatchers.anyInt(), Vote.QUESTION_DOWN) 

只需使用真实的Int而不是ArgumentMatchers.anyInt() 。 喜欢

 presenter.vote(0, Vote.QUESTION_DOWN) 

例如,匹配模拟对象上的参数时使用匹配器

 val calulator = (mock with Mockito) when(calculator.divideByTwo(anyInt()).thenReturn(1) 

将意味着calculator.divideByTwo(int: Int)在用任何Int调用时返回1

当调用真实对象的方法来测试它们(就像你对演示者做的那样),你可以使用真实的参数。