Mat
Mat

Reputation: 515

Mocking a static class field using JMockit

I have re-factored a class and I am currently trying to update Unit Tests to reflect this. One addition to the class is a static field as shown below:

private static JdbcTempate jdbcTemple = DbConfiguration.getJdbcTemplate();

When running the unit tests after adding this field I was getting null pointer errors. I resolved this by mocking the field using powermock with the createMock() and WhiteBox.setInternalState() methods, easy enough.

However one of the suite of tests uses JMockit instead of powermock and mockito. Would anyone be able to show me how I can mock this field using JMockit?

Upvotes: 2

Views: 5923

Answers (2)

Rogério
Rogério

Reputation: 16380

The test can easily be written with JMockit:

@Test
public void setStaticField(@Mocked JdbcTemplate mockTemplate)
{
    Deencapsulation.setField(ClassUnderTest.class, mockTemplate);

    assertSame(mockTemplate, ClassUnderTest.getJdbcTemplate());
}

The mockit.Deencapsulation class is equivalent to WhiteBox, including in the ability to set static final fields.

Upvotes: 3

Jojo.Lechelt
Jojo.Lechelt

Reputation: 1279

Not sure if this is what you want, but you could mock DbConfiguration and train it to return the desired value for the method getJdbcTemplate:

In you TestClass add:

 @Mocked
 private DbConfiguration dbConfiguration;

In your testMethod add:

new NonStrictExpectations() {{
    DbConfiguration.getJdbcTemplate();
    result = new JdbcTemplate( "mock" ); // or return what ever you want your private field to  contain...
}};

When instantiating your ClassUnderTest which owns this private static field, the field than has the value defined by "result = ...".

Upvotes: 1

Related Questions