Groovy Testing using MockFor to test MultipartFile

Recently, I came across a situation where I had to test a service that took a file and uploaded it to a server NAS. service was being passed a “MultipartFile” (org.springframework.web.multipart.MultipartFile)
I wanted to test the service and mock up MultipartFile, as I performed multiple search on “Bingle”, they all pointed to MockMultipartFile. For the unit test I had, I only had to make sure few methods in MultipartFile was called.
I have been using Mockito for a while now and I really loved the simplicity that Mockito provided. However, Mockito won’t support Groovy classes yet :(.
So went back to Groovy’s “MockFor” feature.
Here is how I created a mocked MultipartFile using MockFor and was able to verify the method calls.

import groovy.mock.interceptor.MockFor
import org.springframework.web.multipart.MultipartFile
void testsample(){
		def mockMultipartFile = new MockFor(MultipartFile)
		mockMultipartFile.demand.isEmpty{return false}

		def mockMPF = mockMultipartFile.proxyInstance()
		assertEquals(false, mockMPF.isEmpty())
		mockMultipartFile.verify(mockMPF)  // verifying that .isEmpty was actually called

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s