J'utilise JUnit, Mockito et MockMvc de Spring pour écrire un test unitaire qui teste la possibilité de lire un fichier GridFSDBFile, puis d'écrire dans le contenu d'une réponse. Il ne peut pas lire le InputStream raillé à partir de GridFSDBFile raillé, mais il peut lire la longueur mockée ?! Où ai-je tort?Impossible de lire un InputStream mocké à partir de GridFSDBFile mocké
Controller:
...
@Controller
public class FileReadController {
@Autowired
private IFileService fileService;
@RequestMapping(value = "/v0/files/{fileid}", method = RequestMethod.GET)
public @ResponseBody void read(@PathVariable String fileid, HttpServletResponse res) throws IOException {
GridFSDBFile file = this.fileService.find(fileid);
res.setContentLength((int) file.getLength());
IOUtils.copy(file.getInputStream, res.getOutputStream());
System.out.println("file's length:" + file.getLength());
System.out.println("file's content:" + IOUtils.toString(file.getInputStream()));
}
}
...
ControllerTest:
...
public class FileReadControllerTest {
private MockMvc mockMvc;
@Mock
private FileService mockFileService;
@InjectMocks
private FileReadController mockReadController;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
this.mockMvc = MockMvcBuilders.standaloneSetup(mockReadController).build();
}
@Test
public void shouldReadSuccessfully() throws Exception {
GridFSDBFile file = createFile();
String expectedString = IOUtils.toString(file.getInputStream());
when(mockFileService.find(anyString())).thenReturn(file);
this.mockMvc.perform(get("/v0/files/fileId"))
.andExpect(status().isOk())
.andExpect(content().string(expectedString));
}
private GridFSDBFile createFile() throws IOException {
String content = "this is the fake content";
GridFSDBFile file = mock(GridFSDBFile.class);
when(file.getInputStream()).thenReturn(IOUtils.toInputStream(content));
when(file.getLength()).thenReturn((long) content.length());
when(file.getContentType()).thenReturn("application/x-rpm");
return file;
}
}
...
et il est l'échec:
java.lang.AssertionError: Response content expected:<this is the fake content> but was:<>
sortie de la console:
...
file's length:24
file's content: //nothing
...
Quand j'étudie file.getInputStream() en mode débogage, il montre quelque chose là-dedans:
file.getInputStream();
- buf [116, 104, 105, 115, 32, ...]
- count 24
- mark 0
- pos 24
donc je ne peux pas comprendre pourquoi je ne peux pas convertir cette chaîne fluxEntrée à même il y a un contenu en elle ...
quelques dépendances
org.springframework.boot:spring-boot-starter-web:0.5.0.M4
org.apache.commons:commons-io:1.3.2
junit:junit:4.11
org.mockito:mockito-all:1.9.5
org.springframework:spring-test:3.2.4.RELEASE