[英]Unit test in spring using Mockito
Today while working with Mockito and spring I got struck with this scenario, 今天和Mockito一起工作时,春天,我对这种情况感到震惊,
public class MyClass {
private MyService myService;
int doSomethingElse(String str) {
.....
myService.doSomething(str);
...
}
}
public interface MyService {
String doSomething(String str);
}
public class Class1 {
private MyClass myClass;
public Stirng methodToBeTested() {
myClass.doSomethingElse("..");
}
}
public class class1Test {
@Mock
MyService myService;
@Resource
@Spy
@InjectMocks
MyClass myClass;
@Resource
@InjectMocks
Class1 class1;
public void setUPTest() {
MockitoAnnotations.initMocks(this);
}
@Test
public void methodToBeTestedTest() {
this.setUPTest();
...
class1.methodToBeTested();
}
}
Here I want to mock "MyService". 在这里,我要模拟“ MyService”。 But MyService is used in "MyClass" and it is used in "Class1" . 但是MyService在“ MyClass”中使用,而在“ Class1”中使用。
I want to initialise "MyClass" and "Class1" using spring. 我想使用spring初始化“ MyClass”和“ Class1”。
When I try to run this test, I got the following exception 当我尝试运行此测试时,出现以下异常
org.mockito.exceptions.base.MockitoException: Cannot mock/spy class $Proxy79 Mockito cannot mock/spy following: - final classes - anonymous classes - primitive types org.mockito.exceptions.base.MockitoException:无法模拟/间谍类$ Proxy79 Mockito无法模拟/间谍以下:-最终类-匿名类-基本类型
Can anyone help me with this? 谁能帮我这个?
You are testing Class1
, which only has MyClass
as dependency. 您正在测试Class1
,它仅将MyClass
作为依赖项。 MyService
is irrelevant to this test. MyService
与该测试无关。 You should mock MyClass
and test the call to doSomethingElse
. 您应该模拟MyClass
并测试对doSomethingElse
的调用。
If you wish to test the call to doSomething
of MyService
, you should write a MyClassTest
which mocks the dependency to MyService
. 如果您希望测试对MyService
doSomething
的调用,则应编写一个MyClassTest
对MyService
的依赖关系。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.