HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Mocking utility class for database testing

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
mockingutilitydatabasetestingforclass

Problem

I have these classes that have a boilerplate way of initialization. So, instead of writing it each time, I wrote a class called MockUtil.java, and I put the boilerplate mocks in there.

MockUtil has static variables and methods which can be called to do the mocking for the test classes. So, when writing a new test class setup, MockUtil's setup, boilerplate expectations, replays, and verifications of mock are being called from the Test class.

I feel like this reduces a lot of boilerplate burden on the test classes. But, I still feel like the code structure/code pattern can be improved. I am not sure if it has to be a util class or something else, because two tests can't run simultaneously because of static variables and methods and I feel like it reduces the scope of enhancements, if any, that has to be done. Could you give me suggestions on what I can improve in my code?

MockUtil.java

```
public class MockUtil {

public static JdbcTransactionImpl transaction;
public static Connection connection;
public static PreparedStatement statement;
public static ResultSet resultSet;

public static Connection getConnection() {
return connection;
}

public static ResultSet getResultSet() {
return resultSet;
}

public static PreparedStatement getStatement() {
return statement;
}

public static void createMocks() {
//more boilerplate mocks to create services to be used in each Test -- which are ignored here.
//boilerplate tx mocks
transaction = createMockBuilder(JdbcTransactionImpl.class)
.addMockedMethod("getConnection").createMock();

connection = createMock(Connection.class);
statement = createMock(PreparedStatement.class);
resultSet = createMock(ResultSet.class);
}

public static void setContextualExpectations(String...sqls) throws Exception {
//boilerplate tx expectations.
expect(context

Solution

You are right about the problem with static variables and methods possibly causing problems in a multithreaded environment. I recommend turning your MockUtil into an abstract class with no static methods and then have your test classes extend that. That way you are guaranteed to have fresh mocks for all your test classes.

Context

StackExchange Code Review Q#27608, answer score: 2

Revisions (0)

No revisions yet.