我试图模拟项目中的一些方法,以便在调用它们时返回特定的值。但当你运行测试时,它们会随着输出而下降:
org.mockito.exceptions.missing.InvalidUseOfMatchersException:参数匹配器的使用无效!需要0个匹配者,记录了1个:->网址:com.hodzi.stackviewer.questions.detail.CquestionDetailPresenterTest.voteTest(QuestionDetailPresenterTest.kt:69)
如果匹配器与原始值组合,则可能会发生此异常://不正确:someMethod(anyObject(),"原始字符串");使用匹配器时,所有参数都必须由匹配器提供。例如://更正:someMethod(anyObject(),eq("匹配器字符串");
如果您在调试模式下运行相同的代码并贯穿所有行,那么当您调用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)
意味着CCD_ 4在用任何CCD_ 6调用时返回CCD_。
当调用真实对象的方法来测试它们时(就像您对演示者所做的那样),您使用真实的参数。