Mocking of a single (native) method?

1,978 views
Skip to first unread message

sven.s

unread,
Oct 22, 2010, 6:10:01 PM10/22/10
to PowerMock
Hi,

I'm using EasyMock and have discovered PowerMock because I need to
mock a native (JSNI) method. The problem is that the native method is
included and called within the class which I would like to test. Is it
possible to mock only the single native method so the rest of the code
can be executed. The native method may not be called because an
UnsatisfiedLinkError would occur.

Here is an example code snippet of my class. I want to test the init
method, but the test fails because executeJSNINativeMethod() throws an
UnsatisfiedLinkError when it is called from a testcase. Therefore I
have to mock the native method.

public class MyClass {
public void init() {
//some code is here which should be tested
executeJSNINativeMethod();
//some code is here which should be tested
}

private native void executeJSNINativeMethod() {
//an UnsatisfiedLinkError would occur when this method is called
from a testcase
}
}

Thank you in advance.

Regards,

Sven S.

Johan Haleby

unread,
Oct 23, 2010, 8:02:31 AM10/23/10
to powe...@googlegroups.com
Hi Sven,

The best thing to do would probably be to introduce an anti-corruption layer between your code and the native method.  E.g. refactor the method call to its own class and inject an instance of it as a member variable in MyClass. Then it's mockable by vanilla EasyMock. If this is not an option for you then you can use a technique called partial mocking or just suppress the method. In your case you could do something like this:

import static org.powermock.api.support.membermodification.MemberModifier.suppress;
import static org.powermock.api.support.membermodification.MemberMatcher.method;

@RunWith(PowerMockRunner.class)
@PrepareForTest(MyClass.class)
public class MyClassTest  {

    @Test
    public void test() {
        suppress(method(MyClass.class, "executeJSNINativeMethod"));

        // Run your test
        new MyClass().init();
        ..
    }
}

/Johan

Sven S.

unread,
Oct 23, 2010, 12:28:25 PM10/23/10
to powe...@googlegroups.com
Hi Johan,

cool, it works! :-) I used the suppress-method to solve the problem.

PowerMock seems to be a great library. Thank you for your support.

Regards,

Sven S.

2010/10/23 Johan Haleby <johan....@gmail.com>

--
You received this message because you are subscribed to the Google Groups "PowerMock" group.
To post to this group, send email to powe...@googlegroups.com.
To unsubscribe from this group, send email to powermock+...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/powermock?hl=en.

Rajesh kumar

unread,
Dec 22, 2015, 8:00:51 AM12/22/15
to PowerMock
Hi Johan,

I also tried .. Working fine. but Code coverage is Zero %. Please help me coverage as well.

Thanks,
Rajesh
Reply all
Reply to author
Forward
0 new messages