android - Mocked method not returning value from test-local variable -
i have written test check if method adding , subtracting coins userdata preference method working correctly. mocked sharedpreferences class , using local variable coins
stores coin amount.
however mocked getint() not seem return correct value of coins: running test addcoinvalid fails (expected: 5, actual: 0). i've made 2 outputs during test:
variable: 1 - mockedreturn: 0
variable: 5 - mockedreturn: 0
the left number value variable , right number mocked getint() returns.
can tell me what's going on? :o
this test:
class userdatatest { var coins = 0 val editor = mock<sharedpreferences.editor>() val sharedprefs = mock<sharedpreferences> { on{ getint("coins", 0) } doreturn coins on { edit() } doreturn editor } val context = mock<context> { on { getsharedpreferences("userdata", 0) } doreturn sharedprefs } val userdata = userdata(context) @before fun initeditormock() { whenever(editor.clear()).thenreturn(editor) whenever(editor.putint(eq("coins"), any<int>())).thenanswer{ invocation -> this.coins = invocation.getargument(1) return@thenanswer editor } } @test fun addcoinvalid() { userdata.setcoins(1) println("variable: "+coins+" - mockedreturn: "+userdata.getcoins()) userdata.addcoins(5) println("variable: "+coins+" - mockedreturn: "+userdata.getcoins()) assertequals(5, userdata.getcoins()) } // ... }
and class tested:
class userdata(context: context) { val settings = context.getsharedpreferences("userdata", 0) fun getcoins(): int { return settings.getint("coins", 0) } fun setcoins(number: int) { settings.edit().clear().putint("coins", number).apply() } fun addcoins(number: int) { if(number < 0) { return } var coins = settings.getint("coins", 0) setcoins(coins+number) } }
when use doreturn coins
, mockito saves value coins
had @ mock set time, is, initial value 0
, , returns saved value ignoring changes actual variable.
to make mock query variable each time function called, use doanswer { ... }
:
on { getint("coins", 0) } doanswer { coins }
Comments
Post a Comment