引入pom:
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-testng</artifactId>
<version>2.0.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito2</artifactId>
<version>2.0.2</version>
<scope>test</scope>
</dependency>
使用方法
mokito使用不再介绍,powermock可以mock静态方法:
@PrepareForTest(ZipUtil.class)
public class ExecutorTest extends PowerMockTestCase {
@InjectMocks
private Executor executor;
@Mock
private FTPService ftpService;
@BeforeMethod
public void setUp() {
MockitoAnnotations.initMocks(this);
}
@Test
public void testExecute() {
PowerMockito.mockStatic(ZipUtil.class);
PowerMockito.mockStatic(FileUtils.class);
PowerMockito.when(FileUtils.listFiles(any(), any(), anyBoolean())).thenReturn(Lists.newArrayList());
executor.execute(instructionDTO);
}
}
遇到问题:
java.lang.NoSuchMethodError: org.mockito.Mockito.framework()Lorg/mockito/Moc
问题原因:
参考这篇文章发现是mockito和powermock版本不一致:
解决方法:
安装maven dependency helper插件和maven helper插件,用于分析依赖
在pom中,点击下方的dependency analyzer,输入mock,查找mockito版本,我之前查找到时1.10.19
右键点击排除,之后手动添加mockito版本:
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-testng</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito2</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<artifactId>mockito-core</artifactId>
<groupId>org.mockito</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>2.23.4</version>
</dependency>