I’m using Mockito 1.9.5, PowerMock 1.5.1, JUnit 4.11, and Spring 3.1.4.RELEASE. I’m trying to write a JUnit test in which I want to mock a private method doing nothing. The private method signature is
public class MyService
{
…
private void myMethod(byte[] data, UserFile userFile, User user)
{
And in my JUnit test I have
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({ "classpath:test-context.xml" })
@PrepareForTest(MyServiceImpl.class)
public class MyServiceIT
{
@Rule
public PowerMockRule rule = new PowerMockRule();
@Autowired
private MyService m_mySvc;
private MyService m_mySvcSpy;
@Before
public final void setup() throws Exception
{
m_mySvcSpy = PowerMockito.spy(m_mySvc);
PowerMockito.doNothing().when(m_mySvcSpy, “myMethod”, Matchers.any(byte[].class), Matchers.any(UserFile.class), Matchers.any(User.class));
Unfortunately, the second line dies with the exception
testUploadFile(org.mainco.subco.user.service.MyServiceIT) Time elapsed: 12.693 sec <<< ERROR!
org.powermock.reflect.exceptions.MethodNotFoundException: No method found with name ‘myMethod’ with parameter types: [ null, null, null ] in class org.mainco.subco.user.service.UserFileService$$EnhancerByMockitoWithCGLIB$$4e52bc77.
at org.powermock.reflect.internal.WhiteboxImpl.throwExceptionIfMethodWasNotFound(WhiteboxImpl.java:1247)
at org.powermock.reflect.internal.WhiteboxImpl.findMethodOrThrowException(WhiteboxImpl.java:985)
at org.powermock.reflect.internal.WhiteboxImpl.doInvokeMethod(WhiteboxImpl.java:882)
at org.powermock.reflect.internal.WhiteboxImpl.invokeMethod(WhiteboxImpl.java:713)
at org.powermock.reflect.Whitebox.invokeMethod(Whitebox.java:401)
at org.powermock.api.mockito.internal.expectation.PowerMockitoStubberImpl.when(PowerMockitoStubberImpl.java:93)
at org.mainco.subco.user.service.MyServiceIT.setup(UserFileServiceIT.java:42)
What is the right way to mock generic arguments for a private method using PowerMockito?
Best Answer
I haven't tested it, but I believe the reason the private method isn't found is that it doesn't exist in the object provided by Spring for the
MyService
interface. This object is a proxy , an instance of a generated class which does not extendMyServiceImpl
; so, there is noprivate myMethod(...)
in it.To avoid the problem, the test should simply not use Spring. Instead, instantiate
MyServiceImpl
directly in thesetup()
method. If the test needs other dependencies to get injected intom_mySvc
, then create mocks for those and let PowerMock inject them.