JMockit – Initializing the class under test and dependencies using @Tested annotation

In today post, I would give you a simple example to demonstrate the use of @Tested annotation and use of invocation count in the expectation block to avoid explicit verification. @Tested annotation would initialize the field of the class under test and wire the dependencies by type. In the example given below, the fileService field will be initialized by @Tested annotation and the dependency thridPartyService is wired with the available injectable field.

The video tutorial for this post can be found here.

Complete source code used in this example can be found at github.

package com.ourownjava.tdd.jmockit;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.rmi.RemoteException;

import com.ourownjava.tdd.mockit.exception.RemoteSaveFailedException;

/**
 * 
 * @author Sanju Thomas
 *
 */
public class FileService {
	
	private ThirdPartyService thirdPartyService;
	
	public void save(final File file) throws FileNotFoundException, RemoteSaveFailedException {
		try {
			thirdPartyService.save(new FileOutputStream(file));
		} catch (RemoteException e) {
			throw new RemoteSaveFailedException(e.getMessage(), e);
		}
	}
}

package com.ourownjava.tdd.jmockit;

import java.io.OutputStream;
import java.rmi.RemoteException;

/**
 * 
 * @author Sanju Thomas
 *
 */
public interface ThirdPartyService {

	public void save(final OutputStream outputStream) throws RemoteException;
}

package com.ourownjava.tdd.jmockit;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.OutputStream;
import java.rmi.RemoteException;

import mockit.Expectations;
import mockit.Injectable;
import mockit.Tested;

import org.junit.Test;

import com.ourownjava.tdd.mockit.exception.RemoteSaveFailedException;

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

	@Tested
	private FileService fileService;
	
	@Injectable
	private ThirdPartyService thirdPartyService;
	
	@Test(expected = RemoteSaveFailedException.class)
	public void shouldSendFileToThirdParty() throws FileNotFoundException, RemoteSaveFailedException, RemoteException{
		new Expectations() {{
			thirdPartyService.save((OutputStream)any); 
			times = 1;
			result = new RemoteException("to test third party service exception");
		}};
		fileService.save(new File("tdd.test"));
	}
	
}

package com.ourownjava.tdd.mockit.exception;

import java.rmi.RemoteException;

/**
 * 
 * @author Sanju Thomas
 *
 */
public class RemoteSaveFailedException extends Exception{
	
	private static final long serialVersionUID = 1L;

	public RemoteSaveFailedException(final String message, final RemoteException remoteException){
		super(message, remoteException);
	}

}

Leave a comment

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