Testing - How to Create a Mock Object

I'm just wondering how I can create a Mock object to test the code, for example:

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

?

thanks

+4
source share
3 answers

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); // do something with the A ... } } 

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); // 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 ... } } 
+9
source

Using the mockito mcking framework, try the following:

  whenNew(MyTest.class) .withArguments(Mockito.anyInt(), Mockito.anyInt()) .thenReturn(new MockedMyTest(param1, param2)); 
+3
source

Use the Ia interface; Then.

 Class A implements Ia; Class MockA implements Ia; private Ia a; 

Then

 public MyMockTest { a = new MockA(100, 100); int result = a.doWork(); assertEquals(200, result); // asuming doWork would add both constructor parameters } 
+2
source

All Articles