Issue
I am working on a spring boot 2.1.3 application which has a service which uses ResourceLoader class to read a text file from the resources directory:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Service;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.List;
import java.util.stream.Collectors;
@Service
public class TestService {
@Autowired
ResourceLoader resourceLoader;
public String testMethod(String test) {
List<String> list = null;
Resource resource = resourceLoader.getResource("classpath:test.txt");
try (BufferedReader buffer = new BufferedReader(new InputStreamReader(resource.getInputStream()))) {
list = buffer.lines().collect(Collectors.toList());
} catch (Exception e) {
System.out.println("error : " + e);
}
if (list.contains(test)) {
return "in file";
}
return "not in file";
}
}
I am writing a unit test for this service using mockito:
@RunWith(MockitoJUnitRunner.class)
@ContextConfiguration()
public class AServiceTest {
@InjectMocks
private TestService cut;
@Test
public void testSuccessfulResponse() {
String actualResponse = cut.method("teststring");
String expectedResponse = getSuccessfulResponse();
assertThat(actualResponse, is(expectedResponse));
}
But when I run the test resourceLoader is null?
How can I test the resourceLoader class in this example.
Solution
I have re-written your test. You should not mock your TestService because you are actually testing it. Here is what I have done.
- mockFile: is a multi-line String that represents your file
- resourceLoader: mocked and set it to return Resource
- mockResource: mocked Resource and set it to return an InputStream of the mockFile.
@Test
public void testSuccessfulResponse() throws IOException {
String mockFile = "This is my file line 1\nline2\nline3";
InputStream is = new ByteArrayInputStream(mockFile.getBytes());
cut = new TestService();
ResourceLoader resourceLoader = Mockito.mock(ResourceLoader.class);
cut.resourceLoader = resourceLoader;
Resource mockResource = Mockito.mock(Resource.class);
Mockito.when(mockResource.getInputStream()).thenReturn(is);
Mockito.when(resourceLoader.getResource(Mockito.anyString())).thenReturn(mockResource);
String actualResult1 = cut.testMethod("line3");
Assert.assertEquals(actualResult1, "in file");
String actualResult2 = cut.testMethod("line4");
Assert.assertEquals(actualResult2, "not in file");
}
Answered By - Amit Phaltankar
Answer Checked By - Senaida (JavaFixing Volunteer)