@Service
public class Topic_Service
{
private String test_help()
{
return "test_help";
}
public String testing()
{
return test_help() + " " + "testing";
}
}
//Test Code
@SpringBootTest
@RunWith(PowerMockRunner.class)
@PrepareForTest(Topic_Service.class)
class Topic_Service_test
{
@InjectMocks
private Topic_Service topic_service = PowerMockito.spy(new
Topic_Service());
@Test
void testing_test() throws Exception
{
PowerMockito.when(topic_service,"test_help").thenReturn("hello");
String s = topic_service.testing();
Assertions.assertEquals("hello testing",s);
}
}
//POM.XML Dependencies
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version> 2.8.47</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>1.7.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito2</artifactId>
<version>1.7.0</version>
<scope>test</scope>
</dependency>
我的测试未通过并显示此错误:-
有人可以帮我吗?预先感谢。警告:发生了非法的反射访问操作警告:org.powermock.reflect.internal.WhiteboxImpl(文件:/home/an.kumar1/.m2/repository/org/powermock/powermock-reflect/1.7.0/powermock-reflect-1.7.0的非法反射访问。 jar)方法java.lang.Object.finalize()警告:请考虑将此报告给org.powermock.reflect.internal.WhiteboxImpl的维护者警告:使用--illegal-access = warn启用有关进一步非法反射访问操作的警告警告:所有非法访问操作将在以后的版本中被拒绝
org.mockito.exceptions.misusing.MissingMethodInvocationException:when()需要一个参数,该参数必须是“模拟的方法调用”。例如:when(mock.getArticles())。thenReturn(articles;
此外,由于以下原因,可能会出现此错误:1.存根:final / private / equals()/ hashCode()方法之一。那些方法[[无法被存根/验证。不支持在非公共父类上声明的模拟方法。2.在when()内部,您不会在模拟对象上调用方法,而是在其他某个对象上调用。
PowerMockito.stub
存根私有方法。下面是如何正确存根私有方法:
PowerMockito.stub(PowerMockito.method(Topic_Service.class,"test_help")).toReturn("hello");
我修改了您的代码,如下所示:
@RunWith(PowerMockRunner.class) @PrepareForTest(Topic_Service.class) public class Topic_ServiceTest { @Test void testing_test() throws Exception { // Setup Topic_Service topic_serviceSpy = PowerMockito.spy(new Topic_Service()); PowerMockito.doReturn("Hello").when(topic_serviceSpy, "test_help"); // exercise String s = topic_serviceSpy.testing(); // verify System.out.println(s); } }
并且我通过传递参数--illegal-access=permit
来运行测试。