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
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 toMyClass
. Also, creating the object in the constructor could easily be replaced by passing in an instance ofA
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 ...
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With