我正在为文件上传/下载Rest服务编写junit测试。调用“ gridFSBucket.find(eq(objectId))。first();进入NPE。 我从以前的帖子中知道Bson没有实现eq。因此,我一直在使用Document。我也尝试使用Mockito的do return方法来代替,但这似乎没有用。感谢您的支持。
"doReturn(gridFSFindIterable).when(gridFSBucket).find(doc);"
FileRest设置参数
private MockMvc mockMvc;
private Logger logger = LoggerFactory.getLogger(GridfsApplicationTests.class);
@Spy
GridFSBucket gridFSBucket;
@Mock
MongoConfig mongoConfig;
@InjectMocks
private FileUploadRestController fileUploadRestController;
private GridFS gridFS;
private GridFSFile gridFSFile;
private GridFSDownloadStream gridFSDownloadStream;
private MongoClient mongoClient;
private GridFSFindIterable gridFSFindIterable;
@Before
public void Setup() {
try {
MockitoAnnotations.initMocks(this);
mockMvc = MockMvcBuilders.standaloneSetup(fileUploadRestController).build();
assertNotNull(mockMvc);
fileLicense = new File(String.valueOf(path.toFile()));
gridFS = mock(GridFS.class);
mongoConfig = mock(MongoConfig.class);
gridFSDownloadStream = mock(GridFSDownloadStream.class);
mongoClient = mock(MongoClient.class);
gridFSFile = mock(GridFSFile.class);
gridFSFindIterable = mock(GridFSFindIterable.class);
} catch (NullPointerException npe) {
logger.warn("Unable to read file: {}", path, npe);
}
assertThat(fileLicense).exists();
}
FindRestController端点
@GetMapping("/find/")
public ResponseEntity<?> findFile(@RequestParam("id") String id) {
ObjectId objectId = new ObjectId(id);
JSONObject jsonObject = new JSONObject();
GridFSFile file = gridFSBucket.find(eq(objectId)).first();
if (file != null) {
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
jsonObject.put("file", file.getId().toString());
return new ResponseEntity<>(jsonObject.toString(), httpHeaders, HttpStatus.OK);
}
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
Junit测试用例的发现:
@Test
public void testFindFile_givenObjectId_ReturnSuccessful() throws IOException {
// given
String id = "5c87b948ff03f91885cedb25";
Document doc = new Document("test.txt", fileLicense);
doc.append("id", id);
Mockito.when(gridFSBucket.find(any(Bson.class))).thenReturn(gridFSFindIterable);
Mockito.when(gridFSFindIterable.first()).thenReturn(gridFSFile);
// when
try {
MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders
.get("/fileupload/find/?id=5c87b948ff03f91885cedb25")
.contentType(MediaType.APPLICATION_JSON)
.accept("*");
MvcResult result = mockMvc.perform(requestBuilder).andDo(print()).andReturn();
MockHttpServletResponse response = result.getResponse();
// then
Assert.assertEquals("response status is wrong", 200, response.getStatus());
} catch (Exception e) {
e.printStackTrace();
}
}
NPE错误:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1013)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:897)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882)
at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:71)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:166)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:133)
at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:182)
at com.parsons.gridfs.GridfsApplicationTests.testFindFile_givenObjectId_ReturnSuccessful(GridfsApplicationTests.java:233)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.mockito.internal.runners.DefaultInternalRunner$1.run(DefaultInternalRunner.java:79)
at org.mockito.internal.runners.DefaultInternalRunner.run(DefaultInternalRunner.java:85)
at org.mockito.internal.runners.StrictRunner.run(StrictRunner.java:39)
at org.mockito.junit.MockitoJUnitRunner.run(MockitoJUnitRunner.java:163)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by: java.lang.NullPointerException
at com.parsons.gridfs.FileUploadRestController.findFile(FileUploadRestController.java:120)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:189)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:800)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1038)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005)
... 36 more
答案 0 :(得分:0)
标记为已解决。我在响应中返回了文件对象,而不是GridFSFile的object.getId()。toString();。