使用 Mockito 跳过方法执行
我正在使用 Mockito 进行单元测试,并且我想跳过方法的执行。
我参考了这张票使用 Mockito 跳过行的执行。在这里,我假设 doSomeTask() 和 createLink() 方法位于不同的类中。但就我而言,这两种方法都在同一个类中(ActualClass.java)。
//Actual Class
public class ActualClass{
//The method being tested
public void method(){
//some business logic
validate(param1, param2);
//some business logic
}
public void validate(arg1, arg2){
//do something
}
}
//Test class
public class ActualClassTest{
@InjectMocks
private ActualClass actualClassMock;
@Test
public void test_method(){
ActualClass actualClass = new ActualClass();
ActualClass spyActualClass = Mockito.spy(actualClass);
// validate method creates a null pointer exception, due to some real time data fetch from elastic
doNothing().when(spyActualClass).validate(Mockito.any(), Mockito.any());
actualClassMock.method();
}
}
由于执行 validate 方法时会出现空指针异常,因此我尝试通过监视 ActualClass 对象来跳过方法调用,如上面提到的票证中所述。尽管如此,问题仍未解决。验证方法被执行并创建一个空指针异常,因此无法覆盖实际的测试方法。
那么,如何跳过同一类中的 validate() 方法的执行。
I’m using Mockito for unit testing and I want to skip the execution of a method.
I referred to this ticket Skip execution of a line using Mockito. Here, I assume doSomeTask() and createLink() methods are in different classes. But in my case, both the methods are in the same class (ActualClass.java).
//Actual Class
public class ActualClass{
//The method being tested
public void method(){
//some business logic
validate(param1, param2);
//some business logic
}
public void validate(arg1, arg2){
//do something
}
}
//Test class
public class ActualClassTest{
@InjectMocks
private ActualClass actualClassMock;
@Test
public void test_method(){
ActualClass actualClass = new ActualClass();
ActualClass spyActualClass = Mockito.spy(actualClass);
// validate method creates a null pointer exception, due to some real time data fetch from elastic
doNothing().when(spyActualClass).validate(Mockito.any(), Mockito.any());
actualClassMock.method();
}
}
Since there arises a null pointer exception when the validate method is executed, I’m trying to skip the method call by spying the ActualClass object as stated in the ticket I mentioned above. Still, the issue is not resolve. The validate method gets executed and creates a null pointer exception due to which the actual test method cannot be covered.
So, how do I skip the execution of the validate() method that is within the same class.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
调用
method()
时,您必须始终使用您的间谍类。在实践中,
您必须使用
You must always use your spy class when calling
method()
.In practice, instead of
you must use
如果有任何外部依赖项,可以同时使用以下两个注释。
@InjectMocks
@间谍
这实际上会窥探原始方法。
如果要跳过的方法存在于其他文件中,请使用@Spy注释要跳过的方法存在的类的对象。
In case of any external dependencies the following two annotations can be used at once.
@InjectMocks
@Spy
This will actually spy the original method.
If the method you want to skip exists in some other file, annotate the object of the class with @Spy in which the method to be skipped exists.