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
		}
Advertisements