Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EasyMock and JNA - Mock Generic Return Type

I am trying to mock the following JNA call using EasyMock

convInterface = (ConvInterface)  Native.loadLibrary(libraryLocation,ConvInterface.class);

Using this test method

@Test
public void testLib() {
    Capture<Class<?>> myClassCapture  = EasyMock.newCapture();
    PowerMock.mockStatic(Native.class);

    EasyMock.expect(Native.loadLibrary(EasyMock.isA(String.class), EasyMock.capture(myClassCapture))).andReturn(mockConvInterface);
    PowerMock.replay(Native.class);

    ConvServiceImpl myLib = new ConvServiceImpl();
    myLib.instantiateConvLibrary();

    PowerMock.verify(Native.class);
}

I am getting the following error using version 4.3.0 of the JNA library

The method andReturn(capture#1-of ?) in the type IExpectationSetters<capture#1-of ?> is not applicable for the arguments (ConvInterface)

The same code is fine with version 4.2.0 of the JNA library

Here are the method signatures for the method I am trying to mock

Version 4.2.0

public static Object loadLibrary(String name, Class interfaceClass) {

Version 4.3

public static <T> T loadLibrary(String name, Class<T> interfaceClass) {

How do I go about mocking the return of a generic return type using EasyMock?

Thanks Damien

like image 869
Damien Avatar asked Aug 06 '17 11:08

Damien


1 Answers

The problem comes from your typing of Capture<Class<?>>. This wildcard means you want to capture something. Let's call this something capture#1. So loadLibrary is getting a class of capture#1 in parameter and to return a capture#1 instance. So andReturn expects a capture#1 in parameter.

But you are passing a ConvInterface which isn't (obviously) a capture#1.

The solution is easy. Just do Capture<Class<ConvInterface>> myClassCapture = EasyMock.newCapture(); since this is what you expect loadLibrary to get.

like image 64
Henri Avatar answered Sep 24 '22 12:09

Henri