测试调用本机方法的代码

kay*_*ahr 10 java junit easymock mockito powermock

我有一个这样的课:

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

    public String toString()
    {
        return "Bar: " + getBar();
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,getBar()是使用JNI实现的,并且该类是final.我想写一个junit测试来测试toString()方法.为此,我需要模拟getBar()方法,然后运行原始的toString()方法来检查输出.

我的第一个想法是,这一定是不可能的,但后来我发现PowerMock支持根据功能列表测试最终类和本机方法.但到目前为止,我没有成功.我管理的最好的事情是模拟完整的类,但测试测试了模拟的toString()方法,而不是真正的那个没有多大意义的方法.

那么我如何使用PowerMock 从上面测试这个toString()方法呢?我更喜欢将PowerMock与Mockito一起使用,但如果不可能,我可以使用EasyMock.

kay*_*ahr 8

找到了.我这样做的方式是正确的.我唯一遗漏的是告诉模拟对象在调用toString时调用原始方法().它的工作原理如下:

@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());
    }
}
Run Code Online (Sandbox Code Playgroud)