如何使用 Mockito 注释注入 @Value 构造函数参数
How to inject @Value constructor parameter using Mockito annotation
我有一个 class:
public class MyClass{
MyClass(
@Value("${my.protocol}") String protocol,
@Value("${my.host}") String host,
@Value("${my.port}") int port,
@Autowired MyService myservice) {
........
}
....
}
然后我写了一个使用 Mockito 的测试:
@ExtendWith(MockitoExtension.class)
class MyClassTest {
@Mock
private MyService myservice;
@InjectMocks
private MyClass myClass;
....
}
测试失败:
org.mockito.exceptions.base.MockitoException:
Cannot instantiate @InjectMocks field named 'myClass'! Cause: the type 'MyClass ' has no default constructor
You haven't provided the instance at field declaration so I tried to construct the instance.
Examples of correct usage of @InjectMocks:
@InjectMocks Service service = new Service();
@InjectMocks Service service;
//and... don't forget about some @Mocks for injection :)
我认为这是因为我只提供了4个构造参数中的一个,而没有提供其他三个带有@Value注解的参数。
有人可以告诉我如何注入三个 @Value 构造参数才能使其工作吗?
我使用 Junit 5 和 Mockito。
基于注释的魔法很炫酷,但它并不是解决所有问题的方法。以老式的方式做事:
@BeforeEach
void setup() {
this.subject = new MyClass("http", "localhost", 5000, mockService);
}
Mockito 使用反射来初始化您的实例,因此在初始化步骤中不会发生注入,它只会获取构造函数并在其上发出 #invoke()
方法。
在这种情况下你应该做的是模拟值而不是模拟整个容器,这里的容器是 MyClass
.
我假设您正在使用 .yml
或 .properties
文件来分配值,通过创建新的 application-${env}.yml
这样您将分别获得测试值来自产品环境值。
或者如果您对每种情况都有不同的值,则在每次将上下文中的 MyClass
实例替换为您修改的实例之前:
@BeforeEach
void beforeEach() {
MyClass bean =// get the context and get a reference of `MyClass` bean
bean = new MyClass(...);
}
我有一个 class:
public class MyClass{
MyClass(
@Value("${my.protocol}") String protocol,
@Value("${my.host}") String host,
@Value("${my.port}") int port,
@Autowired MyService myservice) {
........
}
....
}
然后我写了一个使用 Mockito 的测试:
@ExtendWith(MockitoExtension.class)
class MyClassTest {
@Mock
private MyService myservice;
@InjectMocks
private MyClass myClass;
....
}
测试失败:
org.mockito.exceptions.base.MockitoException:
Cannot instantiate @InjectMocks field named 'myClass'! Cause: the type 'MyClass ' has no default constructor
You haven't provided the instance at field declaration so I tried to construct the instance.
Examples of correct usage of @InjectMocks:
@InjectMocks Service service = new Service();
@InjectMocks Service service;
//and... don't forget about some @Mocks for injection :)
我认为这是因为我只提供了4个构造参数中的一个,而没有提供其他三个带有@Value注解的参数。
有人可以告诉我如何注入三个 @Value 构造参数才能使其工作吗?
我使用 Junit 5 和 Mockito。
基于注释的魔法很炫酷,但它并不是解决所有问题的方法。以老式的方式做事:
@BeforeEach
void setup() {
this.subject = new MyClass("http", "localhost", 5000, mockService);
}
Mockito 使用反射来初始化您的实例,因此在初始化步骤中不会发生注入,它只会获取构造函数并在其上发出 #invoke()
方法。
在这种情况下你应该做的是模拟值而不是模拟整个容器,这里的容器是 MyClass
.
我假设您正在使用 .yml
或 .properties
文件来分配值,通过创建新的 application-${env}.yml
这样您将分别获得测试值来自产品环境值。
或者如果您对每种情况都有不同的值,则在每次将上下文中的 MyClass
实例替换为您修改的实例之前:
@BeforeEach
void beforeEach() {
MyClass bean =// get the context and get a reference of `MyClass` bean
bean = new MyClass(...);
}