How to test private static methods using JMockit?

We all know to practice better test driven development we should avoid using static behaviors in java. However while you are dealing with legacy code bases you may have to test the static private behaviors/methods independently to make sure that code is working as expected. JMockit testing framework let you do that. The API for testing private and public static behavior/method is the same.

The complete source code can be cloned from github.

JMockit API to test static methods.

Class: mockit.Deencapsulation
Method: public static T invoke(Class classWithStaticMethod,
String methodName, Object… nonNullArgs)

Argument Description
classWithStaticMethod Pass the class that contains the static method.
methodName Name of the static method.
nonNullArgs Arguments for the method.
package com.ourownjava.tdd.mockit;

import java.util.List;

/**
 * 
 * @author Sanju Thomas
 *
 */
public class ClassWithStaticMethods {
	
	private static void privateStaticBehavior(){
		throw new RuntimeException("I am a private static method. Why did you call me?");
	}
	
	public static void publicStaticBehavior(){
		throw new RuntimeException("I am a public static method. Why did you call me?");
	}
	
	private static void privateStaticBehaviorWithArguments(final List tokens){
		for(final char c : "Sanju Thomas".toCharArray()){
			tokens.add(String.valueOf(c));
		}
	}
	
	private static String [] privateStaticBehaviorWithArgumentsAndReturnValue(final String token, final String delimiter){
		return token.split(delimiter);
	}
}

package com.ourownjava.tdd.jmockit;

import static org.junit.Assert.assertEquals;

import java.util.ArrayList;
import java.util.List;

import mockit.Deencapsulation;

import org.junit.Test;

import com.ourownjava.tdd.mockit.ClassWithStaticMethods;

/**
 * 
 * @author Sanju Thomas
 *
 */
public class TestClassWithPrivateStaticMethod {

	@Test(expected = RuntimeException.class)
	public void shouldInvokePrivateStaticMethod(){
		Deencapsulation.invoke(ClassWithStaticMethods.class, "privateStaticBehavior", new Object[] {});
	}
	
	@Test(expected = RuntimeException.class)
	public void shouldInvokePublicStaticMethod(){
		Deencapsulation.invoke(ClassWithStaticMethods.class, "publicStaticBehavior", new Object[] {});
	}
	
	@Test
	public void shouldInvokePrivateStaticMethodWithArguments(){
		final List tokens = new ArrayList();
		Deencapsulation.invoke(ClassWithStaticMethods.class, "privateStaticBehaviorWithArguments", tokens);
		assertEquals(12, tokens.size());
	}
	
	@Test
	public void shouldInvokePrivateStaticMethodWithArgumentsAndReturnValue(){
		final String [] tokens = Deencapsulation.invoke(ClassWithStaticMethods.class, 
				"privateStaticBehaviorWithArgumentsAndReturnValue", new Object[] {"Sanju Thomas", " "});
		assertEquals(2, tokens.length);
		assertEquals("Sanju", tokens[0]);
		assertEquals("Thomas", tokens[1]);
	}
}


Leave a comment

Your email address will not be published. Required fields are marked *