ZZZ*_*ZZZ 5 java junit mockito
我有一堂课:
public class MyClass{
MyClass(
@Value("${my.protocol}") String protocol,
@Value("${my.host}") String host,
@Value("${my.port}") int port,
@Autowired MyService myservice) {
........
}
....
}
Run Code Online (Sandbox Code Playgroud)
然后我编写了一个使用 Mockito 的测试:
@ExtendWith(MockitoExtension.class)
class MyClassTest {
@Mock
private MyService myservice;
@InjectMocks
private MyClass myClass;
....
}
Run Code Online (Sandbox Code Playgroud)
测试失败了:
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 :)
Run Code Online (Sandbox Code Playgroud)
我认为这是因为我只提供了 4 个构造参数之一,而不提供其他三个具有 @Value 注释的参数。
有人可以让我知道如何注入三个 @Value 构造参数才能使其正常工作吗?
我使用 Junit 5 和 Mockito。
基于注释的魔法很华丽,但它并不能解决所有问题。只是用老式的方式做事:
@BeforeEach
void setup() {
this.subject = new MyClass("http", "localhost", 5000, mockService);
}
Run Code Online (Sandbox Code Playgroud)