在单元测试中,如果被测类使用了某些static native接口,会使测试不太好写,因为Native API需要装载某使用Native库。我们可以使用强大的PowerMockito对这些接口进行隔离。
下面是个小例子。
Class with Native Static Method
1 2 3 4 5 6 7 8 9 10 11 12 |
package org.yli.test; /** * Created by yli on 10/2/2015. */ public class NativeClass { public static native int doAdd(int a, int b); public static native int doSub(int a, int b); } |
Class which consumes the native static methods
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
package org.yli.test; /** * Created by yli on 10/2/2015. */ public class Consumer { public int add(int a, int b) { return NativeClass.doAdd(a, b); } public int sub(int a, int b) { return NativeClass.doSub(a, b); } } |
Unit Test
Mock了Static Native方法,并做了Verify.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
package org.yli.test; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import static org.junit.Assert.assertEquals; import static org.powermock.api.mockito.PowerMockito.when; /** * Created by yli on 10/2/2015. */ @RunWith(PowerMockRunner.class) @PrepareForTest(NativeClass.class) public class ConsumerTest { @Test public void testAdd() { PowerMockito.mockStatic(NativeClass.class); when(NativeClass.doAdd(1, 2)).thenReturn(3); Consumer consumer = new Consumer(); assertEquals(3, consumer.add(1, 2)); PowerMockito.verifyStatic(); NativeClass.doAdd(1, 2); } @Test public void testSub() { PowerMockito.mockStatic(NativeClass.class); when(NativeClass.doSub(1, 2)).thenReturn(-1); Consumer consumer = new Consumer(); assertEquals(-1, consumer.sub(1, 2)); PowerMockito.verifyStatic(); NativeClass.doSub(1, 2); } } |
这只是个简单的例子,实际运用中Native方法往往比较复杂。在写单元测试时应该明确被测的对象,把不必要的接口Mock起来,会使测试变得非常清晰。
PS: 此例的Maven dependencies
- junit:junit:4.8.1
- org.powermock:powermock-mockito-release-full:1.6.2