私はプロジェクトでいくつかのメソッドをモックしようとするので、呼び出されたときに特定の値が返されます。 しかし、あなたがテストを実行するとき、彼らは出力に落ちる:モックメソッドのエラー
org.mockito.exceptions.misusing.InvalidUseOfMatchersException:引数マッチャーの 無効な使用!予想0のmatcher、1が記録: - com.hodzi.stackviewer.questions.detail.QuestionDetailPresenterTest.voteTest(QuestionDetailPresenterTest.kt:69)で>: //のmatcherは生の値と組み合わされている場合
この例外が発生することが間違っている: someMethod(anyObject()、 "生の文字列");マッチャーを使用する場合、すべての引数はマッチャーによって提供される必要があります。たとえば、 // 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")
}
}
)
}
}
ありがとう!
presenter.vote(ArgumentMatchers.anyInt(), Vote.QUESTION_DOWN)
ちょうど
ArgumentMatchers.anyInt()
するのではなく、本当の
Int
を使用します。
はい、動作します。ありがとう! –