测试调用本机方法的代码 [英] Testing code which calls native methods
问题描述
我有这样的课程:
public final class Foo
{
public native int getBar();
public String toString()
{
return "Bar: " + getBar();
}
}
请注意 getBar()使用JNI实现,并且该类是 final 。我想编写一个junit测试来测试 toString()方法。为此,我需要模拟 getBar()方法,然后运行原始的 toString()方法来检查输出。
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.
我的第一个想法是,这一定是不可能的,但后来我发现 PowerMock 支持根据功能列表测试最终类和本机方法。但到目前为止,我没有成功。我管理的最好的事情就是模拟完整的类,但测试测试了模拟的 toString()方法,而不是那些没有多大意义的真实方法。
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.
那么如何使用PowerMock从上面测试这个 toString()方法呢?我更喜欢将PowerMock与 Mockito 一起使用,但如果不可行,我可以使用 EasyMock 。
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.
推荐答案
找到了。我这样做的方式是正确的。我唯一遗漏的是告诉模拟对象在调用toString时调用原始方法()。所以它的工作原理如下:
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());
}
}
这篇关于测试调用本机方法的代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!