发票的图像首先由用户通过 POST-image 请求上传,以便稍后在 POST-order 请求中,自动生成发票的发票服务可以获取图像。(存储在数据库中) 但现在按照集成测试的顺序,我在 POST-image/在 test-db 中获取图像时遇到了一些困难。
订购服务:
createOrder(orderDto){
order order = new order();
ininvoiceService.generateInvoicePdf(order.getId());
order.setInvoice(invoice);
}
发票服务:
generateInvoicePdf{
byte[] imageTopPageBytes = imageService.getImage(imageNameTop);
ImageData imageTopPageData = ImageDataFactory.create(imageTopPageBytes);
Image imageTopPage = new Image(imageTopPageData);
}
我按照IntegrationTest的顺序进行了尝试:
@SpringBootTest
@AutoConfigureMockMvc(addFilters = false)
@ActiveProfiles("test")
@Transactional
class OrderIntegrationTest {
@Autowired
MockMvc mockMvc;
@Test
void shouldCreateCorrectOrder() throws Exception {
String requestJsonProduct1 = """
{
"name": "Dorade side",
"category": "fish",
"priceInEur": "36.12",
"packedPerUnit": "c.a 600gr",
"inStock": 7,
"description": "fish descr",
"shortDescription": "fish short descr"
}
""";
String requestJsonProduct2 = """
{
"name": "Vine tomatoes",
"category": "vegitables",
"priceInEur": "3.59",
"packedPerUnit": "1kg",
"inStock": 21,
"description": "vegi's test descr",
"shortDescription": "vegi's test short descr"
}
""";
String requestJsonProduct3 = """
{
"name": "Basil",
"category": "herbs & spices",
"priceInEur": "2.29",
"packedPerUnit": "20gr",
"inStock": 11,
"description": "herbs test descr",
"shortDescription": "herbs test short descr"
}
""";
String requestJsonCustomer = """
{
"company": "Maze",
"address": "10-13 GrosvenorSquare London",
"firstName": "Gordon",
"lastName": "Ramsey",
"dob": "1986-11-08",
"phoneNumber": "0644448888",
"emailAddress": "[email protected]",
"bankAccount": "NLINGB0021222567"
}
""";
String requestJson = """
{
"customerCompany": "Maze",
"products": [{"productName": "Dorade side", "quantity": 3},
{"productName": "Vine tomatoes", "quantity": 2},
{"productName": "Basil", "quantity": 1}]
}
""";
MockMultipartFile imageMultipartFile = new MockMultipartFile(
"file",
"goldencarrotImagekleinste.jpg",
"image/jpeg",
"AXAXAXAX".getBytes()
);
MockMultipartFile imageMultipartFile2 = new MockMultipartFile(
"file",
"Watermerk goldencarot factuur eindopdracht klein.jpg",
"image/jpeg",
"AXAXAXAX".getBytes()
);
this.mockMvc
.perform(MockMvcRequestBuilders.post("/products")
.contentType(APPLICATION_JSON_UTF8)
.content(requestJsonProduct1))
.andDo(MockMvcResultHandlers.print())
.andExpect(MockMvcResultMatchers.status().isCreated());
this.mockMvc
.perform(MockMvcRequestBuilders.post("/products")
.contentType(APPLICATION_JSON_UTF8)
.content(requestJsonProduct2))
.andDo(MockMvcResultHandlers.print())
.andExpect(MockMvcResultMatchers.status().isCreated());
this.mockMvc
.perform(MockMvcRequestBuilders.post("/products")
.contentType(APPLICATION_JSON_UTF8)
.content(requestJsonProduct3))
.andDo(MockMvcResultHandlers.print())
.andExpect(MockMvcResultMatchers.status().isCreated());
this.mockMvc
.perform(MockMvcRequestBuilders.post("/customers")
.contentType(APPLICATION_JSON_UTF8)
.content(requestJsonCustomer))
.andDo(MockMvcResultHandlers.print())
.andExpect(MockMvcResultMatchers.status().isCreated());
this.mockMvc.perform(MockMvcRequestBuilders.multipart("/image")
.file(imageMultipartFile))
.andDo(MockMvcResultHandlers.print())
.andExpect(MockMvcResultMatchers.status().isOk())
this.mockMvc.perform(MockMvcRequestBuilders.multipart("/image")
.file(imageMultipartFile2))
.andDo(MockMvcResultHandlers.print())
.andExpect(MockMvcResultMatchers.status().isOk());
//.andReturn();
this.mockMvc
.perform(MockMvcRequestBuilders.post("/orders")
.contentType(APPLICATION_JSON_UTF8)
.content(requestJson))
.andDo(MockMvcResultHandlers.print())
.andExpect(MockMvcResultMatchers.status().isCreated());
}
}
控制台中的错误:(图像格式未识别)
MockHttpServletResponse:
Status = 200
Error message = null
Headers = [Content-Type:"text/plain;charset=UTF-8", Content-Length:"77"]
Content type = text/plain;charset=UTF-8
Body = File "Watermerk goldencarot factuur eindopdracht klein.jpg" has been uploaded
Forwarded URL = null
Redirected URL = null
Cookies = []
jakarta.servlet.ServletException: Request processing failed: com.itextpdf.io.IOException: Image format cannot be recognized.
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1019)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:914)
at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:590)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:885)
at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:72)
at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:658)
at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:165)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:132)
at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:201)
at nl.novi.eindopdrachtBackenSystemGoldencarrot.controllers.OrderIntegrationTest.shouldCreateCorrectOrder(OrderIntegrationTest.java:161)
at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:104)
at java.base/java.lang.reflect.Method.invoke(Method.java:577)
at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:727)
at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131)
at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:156)
at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:147)
at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:86)
at org.junit.jupiter.engine.execution.InterceptingExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(InterceptingExecutableInvoker.java:103)
at org.junit.jupiter.engine.execution.InterceptingExecutableInvoker.lambda$invoke$0(InterceptingExecutableInvoker.java:93)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37)
at org.junit.jupiter.engine.execution.InterceptingExecutableInvoker.invoke(InterceptingExecutableInvoker.java:92)
at org.junit.jupiter.engine.execution.InterceptingExecutableInvoker.invoke(InterceptingExecutableInvoker.java:86)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$7(TestMethodTestDescriptor.java:217)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:213)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:138)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:68)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:151)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:35)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:54)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:147)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:127)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:90)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:55)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:102)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:54)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:114)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:86)
at org.junit.platform.launcher.core.DefaultLauncherSession$DelegatingLauncher.execute(DefaultLauncherSession.java:86)
at org.junit.platform.launcher.core.SessionPerRequestLauncher.execute(SessionPerRequestLauncher.java:53)
at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:57)
at com.intellij.rt.junit.IdeaTestRunner$Repeater$1.execute(IdeaTestRunner.java:38)
at com.intellij.rt.execution.junit.TestsRepeater.repeat(TestsRepeater.java:11)
at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:35)
at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:232)
at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:55)
Caused by: com.itextpdf.io.IOException: Image format cannot be recognized.
at com.itextpdf.io.image.ImageDataFactory.createImageInstance(ImageDataFactory.java:582)
at com.itextpdf.io.image.ImageDataFactory.create(ImageDataFactory.java:82)
at com.itextpdf.io.image.ImageDataFactory.create(ImageDataFactory.java:91)
at nl.novi.eindopdrachtBackenSystemGoldencarrot.services.InvoiceService.generateInvoicePdf(InvoiceService.java:80)
at nl.novi.eindopdrachtBackenSystemGoldencarrot.services.OrderService.createOrder(OrderService.java:97)
at nl.novi.eindopdrachtBackenSystemGoldencarrot.controllers.OrderController.createOrder(OrderController.java:38)
at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:104)
at java.base/java.lang.reflect.Method.invoke(Method.java:577)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:150)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:118)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:884)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:797)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1081)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:974)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1011)
... 77 more
```
ps. the image is uploaded as a multipartfile and writed compressed in db with JAVA.util.zip deflater & after fetching decompressed with JAVA.util.zip inflater.
(All of the requests doing their work well in postman/browser, so the problem likely has to be in the testcode itself )
POST-image:
public String uploadImage(MultipartFile multipartFile) throws IOException {
String newImageName = multipartFile.getOriginalFilename();
Optional<ImageDataFile> existingDataFile = imageRepos.findByName(newImageName);
if(existingDataFile.isPresent()){
throw new IllegalArgumentException("afbeelding met deze naam bestaat al in database");
}
ImageDataFile imageData = new ImageDataFile();
imageData.setName(multipartFile.getOriginalFilename());
imageData.setType(multipartFile.getContentType());
imageData.setImageData(ImageUtil.compressImage(multipartFile.getBytes()));
ImageDataFile savedImage = imageRepos.save(imageData);
return savedImage.getName();
}
I think this is the best way, to POST required entitys before POST-order itself with
mockMvc
.perform(path:/requiredEntity)
.content(requiredEntityDto)
etc etc.
& the highest coverage?
question 2: good pracice or is there a better way to do this integration testing? ;p
,coding peace
问题可能根本不在于测试代码/不仅是, 我没有将invoiceClass中的byte[]invoiceData注释为大数据对象。
@洛布 byte[] 发票数据;
一切尽在掌握!所有测试均正确通过。 更新了mockMvc集成测试中图像上传的测试代码:
Path imageTopPath = Paths.get( "C:\\Users\\m\\Downloads\\eindopdrachtBackenSystemGoldencarrot\\" + "eindopdrachtBackenSystemGoldencarrot\\src\\images\\goldencarrotImageTopPageInv.jpg");
byte[] fileContent = Files.readAllBytes(imageTopPath);
MockMultipartFile file = new MockMultipartFile("file",
"goldencarrotImagekleinste.jpg",
MediaType.IMAGE_JPEG_VALUE,
fileContent);
this.mockMvc
.perform(multipart("/image")
.file(file)
.contentType(MediaType.MULTIPART_FORM_DATA))
.andDo(MockMvcResultHandlers.print())
.andExpect(status().isOk());