java - Understanding what is going on under the hood of Mockito framework -
i have problem understanding going on in mockito framework here. have next classes
model class
public class keyvalueimpl{ private string key; private string value; public string getkey() { homecoming key; } public void setkey(string key) { this.key = key; } public string getvalue() { homecoming value; } public void setvalue(string value) { this.value = value; } }
"business logic" class
public class valuefinder { public keyvalueimpl findvalueforkey(keyvalueimpl keyvalue){ keyvalue.setvalue("foo"); homecoming keyvalue; } }
utility class homecoming expected result (will mocked)
public class expectationmanager { public string getexpectedvalue(){ homecoming "loremipsumdolorem"; } }
test class
public class valuefindertest { @test public void testmocked() { keyvalueimpl keyvalue = mockito.mock(keyvalueimpl.class); keyvalue = (new valuefinder()).findvalueforkey(keyvalue); expectationmanager expectationmanager = mockito.mock(expectationmanager.class); when(expectationmanager.getexpectedvalue()).thenreturn("somethingdifferenttofoo"); string expectedvalue = expectationmanager.getexpectedvalue(); verify(keyvalue).setvalue(expectedvalue); //fails, expects "foo" gets "somethingdifferenttofoo" -> ok verify(keyvalue).setvalue(expectationmanager.getexpectedvalue()); //no error, why? } }
the interesting thing happens in lastly row of test class:
verify(keyvalue).setvalue(expectationmanager.getexpectedvalue()); //no error, why?
i expect same behaviour in row above
verify(keyvalue).setvalue(expectedvalue); //fails, expects "foo" gets somethingdifferenttofoo" -> ok
however mockito let's me along it. explantation this?
i suspect problem due order of calls. lastly line effectively:
keyvalueimpl tmp = verify(keyvalue); string value = expectationmanager.getexpectedvalue(); tmp.setvalue(value);
if mockito using verify
method phone call marker "the next time mocked method gets called, check it" without validating mock it's called on, it'll expectationmanager.getexpectedvalue()
phone call verified.
while argue confusing behaviour in mockito, i'd also argue it's confusing test - using 1 mock within verification step of feels design smell me. i'd consider using manually-written fakes rather mocks possible, avoid much interaction between mocks.
java junit mockito
No comments:
Post a Comment