java - Mock not properly worked -
i want use tdd in current app , try create tests. in case need send message support, , if ok return true
. when start tests fail, because actual , expected result not same.
when debug test, see, mockito put mocks need, sender.sendsupportmessage()
steel return false. can explain me what's going wrong?
public class supporttests { @rule public mockitorule rule = mockitojunit.rule(); @mock supportcontract.isupportmessagesender sender; @mock currentuseroperations currentuseroperations; private supportmessage stubsupportmessage; private string message; @before public void init(){ message = "message"; stubsupportmessage = new supportmessage(1, message, null); } @test public void testsendmessagetosupportshouldbedone (){ support support = new support(sender, currentuseroperations); when(currentuseroperations.getcurrentusersystemid()) .thenreturn(long.valueof(1)); when(sender.sendsupportmessage(stubsupportmessage)) .thenreturn(true); boolean actualresult = support.sendmessagetosupport(message); assertequals("sending message support failed.", true, actualresult); } } public class support implements supportcontract.isupport { private supportcontract.isupportmessagesender sender; private currentuseroperations currentuseroperations; public support(supportcontract.isupportmessagesender sender, currentuseroperations currentuseroperations) { this.sender = sender; this.currentuseroperations = currentuseroperations; } @override public boolean sendmessagetosupport(string message) { long usersystemid = currentuseroperations.getcurrentusersystemid(); dateformat dateformat = new simpledateformat("dd/mm/yyyy hh:mm:ss"); supportmessage supportmessage = new supportmessage(usersystemid, message, dateformat.format(calendar.getinstance().gettime())); return sender.sendsupportmessage(supportmessage); } }
ok. found solution.
as see, in testmethod use stubsupportmessage
, instantiated in @before init
method.
also, in support
class see supportmessage supportmessage = new supportmessage(...)
, , these support messages not same stubsupportmessage != supportmessage
.
so, need rid of different objects. problem solved code:
when(sender.sendsupportmessage(any(supportmessage.class))).thenreturn(true);
where any
object of supportmessage
class can used.
test class now:
public class supporttests { @rule public mockitorule rule = mockitojunit.rule(); @mock supportcontract.isupportmessagesender sender; @mock currentuseroperations currentuseroperations; private string message; @before public void init(){ message = "message"; } @test public void testsendmessagetosupportshouldbedone (){ support support = new support(sender, currentuseroperations); when(currentuseroperations.getcurrentusersystemid()).thenreturn(long.valueof(1)); when(sender.sendsupportmessage(any(supportmessage.class))).thenreturn(true); boolean actualresult = support.sendmessagetosupport(message); assertequals("sending message support failed.", true, actualresult); } }
Comments
Post a Comment