【发布时间】:2014-05-07 06:34:23
【问题描述】:
我正在使用 JUnit、Mockito 和 Spring 的 MockMvc 编写一个单元测试,测试从服务读取 GridFSDBFile 的能力,然后写入响应的内容。 它无法从模拟的 GridFSDBFile 中读取模拟的 InputStream,但它可以读取模拟的长度?!我哪里错了?
控制器:
...
@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;
}
}
...
它失败了:
java.lang.AssertionError: Response content expected:<this is the fake content> but was:<>
控制台输出:
...
file's length:24
file's content: //nothing
...
当我在调试模式下调查 file.getInputStream() 时,它会在其中显示一些内容:
file.getInputStream();
- buf [116, 104, 105, 115, 32, ...]
- count 24
- mark 0
- pos 24
所以我想不通为什么我不能把这个 inputStream 转换成字符串,即使里面有内容......
一些依赖项
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
【问题讨论】:
标签: java spring mongodb junit mockito