小例子,使用jUnit 4.11,Mockito 2.6.3,PowerMock 1.7.0RC4:
public class TheClass {
public static int giveMeNumber() {
return 70;
}
public static int giveMeThatNumber(int it) {
return it;
}
}
和
import org.junit.Test;
import org.junit.runner.*;
import org.mockito.*;
import org.powermock.api.mockito.*;
import org.powermock.core.classloader.annotations.*;
import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class)
// @PrepareForTest(TheClass.class)
public class TheTestClass {
@Test
@PrepareForTest(TheClass.class)
public void test1() {
PowerMockito.mockStatic(TheClass.class);
Mockito.when(TheClass.giveMeNumber()).thenReturn(13);
System.out.println(TheClass.giveMeNumber());
}
@Test
@PrepareForTest(TheClass.class)
public void test2() {
PowerMockito.mockStatic(TheClass.class);
Mockito.when(TheClass.giveMeThatNumber(25)).thenReturn(50);
System.out.println(TheClass.giveMeThatNumber(25));
}
@Test
public void test3() {
System.out.println("Hey, I do not want a @Prepare...d class!");
}
}
依赖项是用Maven加载的,pom.xml
是:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>stackoverflow.bowi</groupId>
<artifactId>place.of.prepareForTest</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>Place of PrepareForTest</name>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<powermock.version>1.7.0RC4</powermock.version>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>2.6.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>${powermock.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito2</artifactId>
<version>${powermock.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
当我在eclipse中运行这些测试时(右键单击类名,运行为... , JUnit测试),它们通过(实际上没有检查任何内容,我知道:-))。当我运行它们单独(右键单击方法名称,运行为... , JUnit test )时,它们会失败{{1没有任何痕迹。
奇怪的是,当我从方法签名中删除initializationError [Runner: JUnit 4] (0,000s)
并在类签名中取消注释时,所有三个都可以一起运行并且单独运行。
但现在看:@PrepareForTest(TheClass.class)
说它不想要准备好&#34;&#34; test3()
。我认为是正确的,是将TheClass
从类签名移动到需要它的方法的签名(@PrepareForTest(TheClass.class)
和test1()
),就像以前一样但失败了。 / p>
我做错了什么?