Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing code which calls native methods

I have a class like this:

public final class Foo
{
    public native int getBar();

    public String toString()
    {
        return "Bar: " + getBar();
    }
}

Please note that getBar() is implemented with JNI and that the class is final. I want to write a junit test to test the toString() method. For this I need to mock the getBar() method and then run the original toString() method to check the output.

My first thought was that this must be impossible but then I found PowerMock which supports testing final classes and native methods according to the feature list. But so far I had no success with it. The best thing I managed was mocking the complete class but then the test tested the mocked toString() method instead of the real one which doesn't make much sense.

So how can I use PowerMock to test this toString() method from above? I prefer using PowerMock with Mockito but if this is not possible I have no problem with using EasyMock instead.

like image 513
kayahr Avatar asked Feb 06 '11 21:02

kayahr


2 Answers

Found it. The way I was doing it was correct. The only thing I missed was telling the mock object to call the original method when toString was called(). So it works like this:

@RunWith(PowerMockRunner.class)
@PrepareForTest({ Foo.class })
public class FooTest
{
    @Test
    public void testToString() throws Exception
    {
        Foo foo = mock(Foo.class);
        when(foo.getBar()).thenReturn(42);
        when(foo.toString()).thenCallRealMethod();
        assertEquals("Bar: 42", foo.toString());
    }
}
like image 56
kayahr Avatar answered Sep 17 '22 14:09

kayahr


Or use JMockit with dynamic partial mocking:

import org.junit.*;
import mockit.*;

public class FooTest
{
    @Test
    public void testToString()
    {
        final Foo foo = new Foo();
        new Expectations(foo) {{ foo.getBar(); result = 42; }};

        assertEquals("Bar: 42", foo.toString());
    }
}
like image 26
Rogério Avatar answered Sep 19 '22 14:09

Rogério