'How to mock field type Resource of Spring with JUNIT5 and Mockito?
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 ?
Solution 1:[1]
Mockito @Mock does not perform Spring Dependency Injection mechanism. It just creates a mock and assigns it to the resourceFile field inside your test suite.
There are two options:
- Replace field injection with constructor injection and put the value manually.
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);
}
}
- Apply
@SpringBootTestto run the Spring Context and proceed the bean lifecycle.
@SpringBootTest
class MyClassTest{
@Autowired
private MyClass subject;
...
}
Though in this case, you won't be able to mock Resource. Instead, you should put the file with required content to test/resources.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Semyon Kirekov |
