gradleVersion = '4.1'
"org.powermock:powermock-api-mockito:1.6.3"
testCompile("org.powermock:powermock-module-junit4:1.6.3")
Jacoco default version used by Gradle 4.1
空指针异常,同时具有实用程序方法和实例方法的类。我正在尝试自动化类似于它的类。
正在测试的类是:
public class StaticandInstance {
public int age;
public String name;
public static String commonPrefix(int age){
if(age <18)
return "Junior";
if(age > 18 && age< 65)
return "Mr/Miss/Mrs";
if(age>=65)
return "Senior";
return "Sir/Madam";
}
public StaticandInstance(int age,String name){
this.age=age;
this.name=name;
}
public String callPerson(){
return commonPrefix(age)+" " + name;
}
}
测试类是
import static org.junit.Assert.*;
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;
@RunWith(PowerMockRunner.class)
@PrepareForTest({StaticandInstance.class})
public class StaticandInstanceTest {
StaticandInstance instance;
@Test
public void testStaticAndInstance() {
PowerMockito.mockStatic(StaticandInstance.class);
instance= new StaticandInstance(15,"Vikram");
String test = instance.callPerson();
assertEquals(test, "Junior Vikram");
}
}
当我以JUnit执行此命令时,它可以成功运行,但无法在Gradle上运行,并且Jacoco代码覆盖率显示为零。
错误消息是:
java.lang.NullPointerException
at StaticandInstance.<init>(StaticandInstance.java:19)
at testStaticAndInstance(StaticandInstanceTest.java:18)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
假设您的gradle文件没有问题,对于给定的示例,您可以提供。我认为您忘了指定使用参数commonPrefix
调用静态方法15
时应该发生的情况。
检查以下代码和代码中的注释:
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
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;
@RunWith(PowerMockRunner.class)
@PrepareForTest({StaticandInstance.class})
public class StaticandInstanceTest {
StaticandInstance instance;
@Test
public void testStaticAndInstance() {
PowerMockito.mockStatic(StaticandInstance.class);
instance = new StaticandInstance(15, "Vikram");
// You have to specify what happen when the static method you are trying to mock is called.
Mockito.when(StaticandInstance.commonPrefix(15)).thenReturn("Junior");
// Then you can do your actual method call
String test = instance.callPerson();
// And assert
assertEquals(test, "Junior Vikram");
}
}
但是,对于您提供的特定情况,可能根本不需要PowerMockito和静态模拟。
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class StaticandInstanceTest {
StaticandInstance instance;
@Test
public void testMethod() {
instance = new StaticandInstance(15, "Vikram");
// Then you can do your actual method call
String test = instance.callPerson();
// And assert
assertEquals(test, "Junior Vikram");
}
}