0

Possible Duplicate:
junit test class for the following code

How can I write the junit test class for the following code,

package sample;

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);


    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());


} }
Community
  • 1
  • 1
Biplab Mitra
  • 327
  • 2
  • 5
  • 12

1 Answers1

0

So you need to do one of the following options to inject mocks into the fields name and userdao.

  1. Do not call constructors in your code directly but instead use field injection via setters. This will allow your test to provided mocked instances of the two classes.

  2. Provide default scope setter methods for the two fields. These methods would be in place for test purposes only.

  3. Use Refection to set the fields to mocked instances. An easy way to do this is with Spring's ReflectionTestUtils.

Once one of these is in place you can provide mocked instances (maybe using Mockito) to drive the behavior you wish to test. I would suggest that option 1 is the best if fesible, then option 3. However, the disadvantage to options 3 is that the test is dependant of the names of private fields.

John B
  • 32,493
  • 6
  • 77
  • 98