Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing - how to create Mock object [closed]

I am just wondering how can I create Mock object to test code like:

public class MyTest
{
  private A a;
  public MyTest()
  {
     a=new A(100,101);
  }
}

?

Thanks

like image 533
user592704 Avatar asked Nov 28 '12 03:11

user592704


1 Answers

Code that instantiates objects using new directly makes testing difficult. By using the Factory pattern you move the creation of the object outside of the code to be tested. This gives you a place to inject a mock object and/or mock factory.

Note that your choice of MyTest as the class to be tested is a bit unfortunate as the name implies that it is the test itself. I'll change it to MyClass. Also, creating the object in the constructor could easily be replaced by passing in an instance of A so I'll move the creation to a method that would be called later.

public interface AFactory
{
    public A create(int x, int y);
}

public class MyClass
{
    private final AFactory aFactory;

    public MyClass(AFactory aFactory) {
        this.aFactory = aFactory;
    }

    public void doSomething() {
        A a = aFactory.create(100, 101);
        // do something with the A ...
    }
}

Now you can pass in a mock factory in the test that will create a mock A or an A of your choosing. Let's use Mockito to create the mock factory.

public class MyClassTest
{
    @Test
    public void doSomething() {
        A a = mock(A.class);
        // set expectations for A ...
        AFactory aFactory = mock(AFactory.class);
        when(aFactory.create(100, 101)).thenReturn(a);
        MyClass fixture = new MyClass(aFactory);
        fixture.doSomething();
        // make assertions ...
    }
}
like image 133
David Harkness Avatar answered Sep 28 '22 07:09

David Harkness