如何用JUNIT5和Mockito模拟Spring的字段类型Resource?
我有一个从目录中读取 JSON 文件的类,但我无法模拟资源字段:
import org.springframework.core.io.Resource;
public class MyClass{
@Value("classpath:file.json")
private Resource resourceFile;
public MyDTO getInfoFromJSONFile() {
try {
//Read file
} catch (IOException e) {
throw new MyException("General Error");
}
}
这是我的测试:
import org.springframework.core.io.Resource;
@ContextConfiguration({ "classpath:file.json" })
class MyClassTest{
private MyClass subject;
@Mock
private Resource resourceFile;
@BeforeEach
void setUp() {
this.subject = new MyClass();
MockitoAnnotations.initMocks(this);
}
@Test
@ParameterizedTest
@ValueSource(strings = {"myParam"})
void testReadInfoFromJsonFileSuccessfully(String param){
MyDTO myDTO= subject.getInfoFromJSONFile(providerConfigId);
Assertions.assertEquals(myDTO.getMyField(), "VALUE");
}
}
资源文件字段从未使用模拟值初始化,我如何模拟这种类型的字段?
I have a class that reads JSON File from my directory, but I Could't mock the Resource field:
import org.springframework.core.io.Resource;
public class MyClass{
@Value("classpath:file.json")
private Resource resourceFile;
public MyDTO getInfoFromJSONFile() {
try {
//Read file
} catch (IOException e) {
throw new MyException("General Error");
}
}
This my test:
import org.springframework.core.io.Resource;
@ContextConfiguration({ "classpath:file.json" })
class MyClassTest{
private MyClass subject;
@Mock
private Resource resourceFile;
@BeforeEach
void setUp() {
this.subject = new MyClass();
MockitoAnnotations.initMocks(this);
}
@Test
@ParameterizedTest
@ValueSource(strings = {"myParam"})
void testReadInfoFromJsonFileSuccessfully(String param){
MyDTO myDTO= subject.getInfoFromJSONFile(providerConfigId);
Assertions.assertEquals(myDTO.getMyField(), "VALUE");
}
}
The field resourceFile never is initialized with a mock value, How can I mock this type of field ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Mockito
@Mock
不执行 Spring 依赖注入机制。它只是创建一个模拟并将其分配给测试套件中的resourceFile
字段。有两种选择:
但在这种情况下,您将无法模拟
Resource
。相反,您应该将包含所需内容的文件放入test/resources
中。Mockito
@Mock
does not perform Spring Dependency Injection mechanism. It just creates a mock and assigns it to theresourceFile
field inside your test suite.There are two options:
@SpringBootTest
to run the Spring Context and proceed the bean lifecycle.Though in this case, you won't be able to mock
Resource
. Instead, you should put the file with required content totest/resources
.解决方案3:
}
solution 3:
}