I have the following scenario
interface DAO
{
String a();
String b();
String c();
}
I create a mock of this DAO interface and I feed it to something called DAOProcess. Inside DAOProcess, I have various methods calling DAO methods a, b and c.
Now each time I need to unit test a method in DAOProcess, I'll end up writing when(mockDAO.a()).thenReturn("test")
.
Is there anyway I can move these when(mockDAO.a()).thenReturn("test")
common to all the test cases ?
We'll be using JUnit as a unit testing framework, but since Mockito is not bound to JUnit, you can follow along even if you're using a different framework.
JUnit is the Java library used to write tests (offers support for running tests and different extra helpers - like setup and teardown methods, test sets etc.). Mockito is a library that enables writing tests using the mocking approach. Show activity on this post. JUnit is used to test API's in source code.
In this chapter, we'll learn how to integrate JUnit and Mockito together. Here we will create a Math Application which uses CalculatorService to perform basic mathematical operations such as addition, subtraction, multiply, and division. We'll use Mockito to mock the dummy implementation of CalculatorService.
If your test cases are all in one class you could make use of a method annotated with @Before
, e.g.:
...
private DAO mockDAO;
@Before
public void setUp() {
mockDAO = mock(DAO.class);
when(mockDAO.a()).thenReturn("test");
...etc...
}
...
Or, if you need the behaviour over many test classes you could write a utility class to set behaviour on a Mock instance, e.g.:
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.
You can create an AbstractTestCase class that is abstract
and is extended by all test cases where you need this mock. In that 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 concrete test case classes, you would
public class MyConcreteTestCase extends AbstractTestCase
{
@InjectMocks
@Autowired
private DAOProcess daoProcess;
....
}
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