我正在使用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转换为String,即使其中有内容......
某些依赖
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
答案 0 :(得分:0)
您的问题可能是由于mockReadController的初始化不正确引起的。当mockReadController预期为null时,您可以在setUp()方法的开头调用MockitoAnnotations.initMocks(this)。所以不可能将mockFileService注入其中。
尝试这样的事情:
@Before
public void setUp() throws Exception {
mockReadController = Mockito.mock(FileReadController.class);
MockitoAnnotations.initMocks(this);
//your other stuff
}