在单元测试中,如果被测类使用了某些static native接口,会使测试不太好写,因为Native API需要装载某使用Native库。我们可以使用强大的PowerMockito对这些接口进行隔离。
下面是个小例子。
Class with Native Static Method
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
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.
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
作者: bloodlee
又有点迷茫了... 查看bloodlee的所有文章