Is there something similar to the Junit Setup method in Mockito

I have the following script

interface DAO { String a(); String b(); String c(); } 

I am creating a layout for this DAO interface and I pass it under the name DAOProcess. Inside DAOProcess, I have various methods that call DAO methods a, b, and c.

Now every time I need the unit test method in DAOProcess, I will write when(mockDAO.a()).thenReturn("test") .

In any case, can I move these when(mockDAO.a()).thenReturn("test") common to all test cases?

+6
source share
2 answers

If your test cases are in the same class, you can use a method annotated with @Before , for example:

 ... private DAO mockDAO; @Before public void setUp() { mockDAO = mock(DAO.class); when(mockDAO.a()).thenReturn("test"); ...etc... } ... 

Or, if you need behavior across many test classes, you can write a utility class to set the behavior in the Mock instance, for example:

 public class MockDAOPrototype { public DAO getMockWithDefaultBehaviour() { final DAO mockDAO = mock(DAO.class); when(mockDAO.a()).thenReturn("test"); ...etc... return mockDAO; } } 

And then call MockDAOPrototype.getMockWithDefaultBehaviour() in your setUp method.

+9
source

You can create an AbstractTestCase class, which is abstract , and extends with all test cases where you need this layout. In this abstract test case, you will have the following statements.

  @Ignore // just in case your runner thinks this is a JUnit test. public abstract class AbstractTestCase { @Mock private DAO mockDAO; @Before private void setupMocks() { when(mockDAO.a()).thenReturn("test") .... } } 

In your specific test classes, you would

  public class MyConcreteTestCase extends AbstractTestCase { @InjectMocks @Autowired private DAOProcess daoProcess; .... } 
+2
source

All Articles