In the deep trenches with JMockit Part 3
by Eing Ong
This is a continuation from Part 2 on JMockit concepts. In this section, we’ll cover the final important topics as well as references you can continue with.
Mockups
Mockups can be used when you have complex behavior of a class under test and your expectations start to get too convoluted. Note also that this is commonly referred to as a state-based approach.
/**
* Create a class containing all MockUps for UserAccount class.
*/
public class UserAccountMockHelper {
/**
* Create a method to allow user to specify the behavior for the class to be mocked.
* In this case, we're faking Preferences class by faking its implementation.
*/
public void setupUserAccountMockPreferences(final String country) {
new MockUp<Preferences>() {
// Creating the constructor's fake implementation
@Mock
public void $init() {}
// Creating the static initializer blocks fake implementation
@Mock
public void $clinit() {}
// Creating how getPreferences should behave in order to test.
@Mock
public Preferences getPreferences(String attribute) {
...
}
// other MockUp Helpers for UserAccount class …
The Non-accessibles
JMockit provides the capability to set private fields and invoke private methods. This is particularly useful if you work with legacy code base or code that is hard to be refactored.
Source Code | JMockit test code | Description |
---|---|---|
private int intField; | setField(anInstance, “intField”, 123); | Set value of a private field |
private void static staticMethod() {} | invoke(SampleClass.class,”staticMethod”); | Invoke a private static method |
private void instanceMethod(int val) {} | invoke(anInstance,”instanceMethod”, 987); | Invoke a private instance method |
References
This overview of JMockit is by no means exhaustive. You can read more in depth and particularly also “Partial Mocking” and “Using JMockit Code Coverage” in JMockit tutorial that is not covered here. Here are some references that I started out with and still find them very useful today.
- JMockit official guide and tutorial
- JMockit JavaDoc
- Abhinandan's Blog
- Dhruba Bandopadhyay's Blog
- Robert Bor's Blog on comparing Mockito/Powermock/JMockit with coding samples
For previous deep trenches with JMockit -
Subscribe via RSS