我有一个类可以从我的目录中读取 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");
}
}
资源文件字段从未使用模拟值初始化,我如何模拟这种类型的字段?
Mockito
@Mock
不执行Spring依赖注入机制。它只是创建一个模拟并将其分配给测试套件中的 resourceFile
字段。
有两种选择:
public class MyClass{
private Resource resourceFile;
public MyClass(@Value("classpath:file.json") Resource resourceFile) {
this.resourceFile = resourceFile;
}
}
class MyClassTest{
private MyClass subject;
@Mock
private Resource resourceFile;
@BeforeEach
void setUp() {
MockitoAnnotations.initMocks(this);
this.subject = new MyClass(resourceFile);
}
}
@SpringBootTest
运行 Spring Context 并继续 bean 生命周期。@SpringBootTest
class MyClassTest{
@Autowired
private MyClass subject;
...
}
尽管在这种情况下,你将无法嘲笑
Resource
。相反,您应该将包含所需内容的文件放入 test/resources
。
解决方案3:
@ExtendWith(MockitoExtension.class)
class MyClassTest{
@InjectMocks
private MyClass subject;
@Mock
private Resource resourceFile;
@Test
public void tesetMethod(){
ClassLoader classLoader = getClass().getClassLoader();
InputStream inputStream = classLoader.getResourceAsStream("file.json");
Mockito.when(resource.getInputStream()).thenReturn(inputStream);
}
}