Code that creates objects using new directly makes testing difficult. Using the Factory pattern , you move the creation of an object outside of the code being checked. This gives you a place to inject a mock object and / or mock factory.
Please note that your choice of MyTest as a tested class is a bit unfortunate, as the name implies that this is the test itself. I will change it to MyClass . In addition, creating an object in the constructor can easily be replaced by passing in an instance of A , so I will translate the creation into a method that will 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);
Now you can pass the factory layout in a test that will create a layout A or A of your choice. Let me use Mockito to create a factory layout.
public class MyClassTest { @Test public void doSomething() { A a = mock(A.class);
source share