Testing - how to create Mock object

java, mocking, unit-testing

Solution

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 ...
    }
}

Problem

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

Original source