在单元测试中使用PowerMockito隔离static native method

在单元测试中,如果被测类使用了某些static native接口,会使测试不太好写,因为Native API需要装载某使用Native库。我们可以使用强大的PowerMockito对这些接口进行隔离。

下面是个小例子。

Class with Native Static Method

Class which consumes the native static methods

Unit Test

Mock了Static Native方法,并做了Verify.

这只是个简单的例子,实际运用中Native方法往往比较复杂。在写单元测试时应该明确被测的对象,把不必要的接口Mock起来,会使测试变得非常清晰。

PS: 此例的Maven dependencies

  • junit:junit:4.8.1
  • org.powermock:powermock-mockito-release-full:1.6.2