How to mock the object for the Phone object.
code bellow,
public class Fortest {
UserDao userdao = new UserDao();
Phone name = new Phone();
public String handleUser(User user) {
String returncode="failed";
//User usr = new User("bob");
String username=user.getUsername();
String pass=user.getPass();
System.out.println("username and password : "+username+" : "+pass);
Phone name = new Phone();
String ph = name.getA();
System.out.println("ph "+ph);
if(ph.equalsIgnoreCase("test")){
System.out.println("A "+ph);
returncode="done";
}
System.out.println("returning "+returncode);
return returncode;
//System.out.println("name "+name.toString());
//System.out.println(name.getA());
}
}
Thanks
First I’m going to make some assumptions.
user.getUsername()&user.getPass()have no side affects.The
System.out.printlnare not important to you.Thus done your class becomes:
So your test has two conditions. Either
phone.getA()is “test” and you return “done” or it is not and you return “failed”.So how to set set “
getA“. One thing is for sure, we will need to be able set “name” from the test. For that we need to “inject” it (we can do it a number of other ways, but I loves injection). I’d use Guice, many would use Spring. Some would use one of the other injection frameworks. But in the tests most of us would use manual injection.Now the tests are fairly simply:
The implementation of
setPhoneIntoTestMode/setPhoneIntoLiveModewill depend on how complexPhoneis. If it is complex than we would look at “facking” it in some way (mocks, stubs, etc). This could be a chunk of code you write, it could be using a tool like Mocketo.If the Phone object is simple, and has or can have a “
setA” method, then just use that.I’m sure later you will need
userdao. The same thing will be done at that point. Inject and mock/setup the object.