Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/377.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/user-interface/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 我的单元测试用例在spring boot中的PUT api控制器失败_Java_Spring Boot - Fatal编程技术网

Java 我的单元测试用例在spring boot中的PUT api控制器失败

Java 我的单元测试用例在spring boot中的PUT api控制器失败,java,spring-boot,Java,Spring Boot,我已经创建了一个基本的CRUDAPI。我已经为所有的api编写了测试用例,每个测试用例都可以很好地工作,但不能放在一起。它总是给我资源找不到的错误 型号 package com.example.crudrestapi.model; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import javax.persiste

我已经创建了一个基本的CRUDAPI。我已经为所有的api编写了测试用例,每个测试用例都可以很好地工作,但不能放在一起。它总是给我资源找不到的错误

型号

package com.example.crudrestapi.model;


import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Data
@Entity
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class Customer {

    @Id
    @GeneratedValue private Long id;
    private String name;
    private String address;
    private String phoneNumber;
    private String gstin;
    private float outstandingBalance;
}
测试

@ExtendWith(SpringExtension.class)
@WebMvcTest(CrudController.class)
class CrudControllerTest {

    @Autowired
    MockMvc mockMvc;

    @MockBean
    CustomerRepo customerRepo;
    
    @Test
    void putApiTest() throws Exception {

        Customer customer = Customer.builder().build();
        given(customerRepo.findById(Long.parseLong("1"))).willReturn(Optional.of(customer));

        mockMvc.perform(put("/customers/{customerId}", 1)
                .content("{ \"name\" : \"test\", \"address\" : \"test\" }")
                .contentType(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk());
    }
控制器

@PutMapping("customers/{customerId}")
    public Customer updateCustomer(@RequestBody Customer newCustomer, @PathVariable Long customerId) throws ResourceNotFoundException {

        return customerRepo.findById(customerId)
                .map(customer -> {
                    if (newCustomer.getName() != null)
                        customer.setName(newCustomer.getName());
                    if (newCustomer.getGstin() != null)
                        customer.setGstin(newCustomer.getGstin());
                    if (newCustomer.getPhoneNumber() != null)
                        customer.setPhoneNumber(newCustomer.getPhoneNumber());
                    if (newCustomer.getAddress() != null)
                        customer.setAddress(newCustomer.getAddress());
                    if (newCustomer.getOutstandingBalance() != 0.0f)
                        customer.setOutstandingBalance(newCustomer.getOutstandingBalance());
                    return customerRepo.save(customer);
                }).orElseThrow( () ->new ResourceNotFoundException());

    }
我收到错误信息

2020-12-29 08:36:04.789  INFO 2564 --- [           main] c.e.c.controller.CrudControllerTest      : Starting CrudControllerTest using Java 11.0.9 on Acer-Aspire7 with PID 2564 (started by Ashil in C:\Users\Ashil\Documents\Java+SpringBoot\crudRestApi)
2020-12-29 08:36:04.792  INFO 2564 --- [           main] c.e.c.controller.CrudControllerTest      : No active profile set, falling back to default profiles: default
2020-12-29 08:36:06.607  INFO 2564 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2020-12-29 08:36:07.103  INFO 2564 --- [           main] o.s.b.t.m.w.SpringBootMockServletContext : Initializing Spring TestDispatcherServlet ''
2020-12-29 08:36:07.103  INFO 2564 --- [           main] o.s.t.web.servlet.TestDispatcherServlet  : Initializing Servlet ''
2020-12-29 08:36:07.106  INFO 2564 --- [           main] o.s.t.web.servlet.TestDispatcherServlet  : Completed initialization in 3 ms
2020-12-29 08:36:07.155  INFO 2564 --- [           main] c.e.c.controller.CrudControllerTest      : Started CrudControllerTest in 2.943 seconds (JVM running for 5.294)

MockHttpServletRequest:
      HTTP Method = PUT
      Request URI = /customers/1
       Parameters = {}
          Headers = [Content-Type:"application/json;charset=UTF-8", Content-Length:"39"]
             Body = { "name" : "test", "address" : "test" }
    Session Attrs = {}

Handler:
             Type = com.example.crudrestapi.controller.CrudController
           Method = com.example.crudrestapi.controller.CrudController#updateCustomer(Customer, Long)

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = java.lang.IllegalStateException

ModelAndView:
        View name = null
             View = null
            Model = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 404
    Error message = null
          Headers = [Content-Type:"text/plain;charset=UTF-8", Content-Length:"18"]
     Content type = text/plain;charset=UTF-8
             Body = Resource Not Found
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

java.lang.AssertionError: Status expected:<200> but was:<404>
Expected :200
Actual   :404
<Click to see difference>


    at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:59)
    at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:122)
    at org.springframework.test.web.servlet.result.StatusResultMatchers.lambda$matcher$9(StatusResultMatchers.java:627)
    at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:196)
    at com.example.crudrestapi.controller.CrudControllerTest.putApiTest(CrudControllerTest.java:85)
    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.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:688)
    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:149)
    at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:140)
    at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:84)
    at org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)
    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.ExecutableInvoker.invoke(ExecutableInvoker.java:104)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$6(TestMethodTestDescriptor.java:210)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:206)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:131)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:65)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1541)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:143)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1541)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:143)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:108)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:88)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:54)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:67)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:52)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:96)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:75)
    at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:71)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
    at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:220)
    at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:53)

2020-12-29 08:36:07.506  INFO 2564 --- [extShutdownHook] o.s.s.concurrent.ThreadPoolTaskExecutor  : Shutting down ExecutorService 'applicationTaskExecutor'

Process finished with exit code -1
2020-12-29 08:36:04.789信息2564-[main]c.e.c.controller.CrudControllerTest:在带有PID 2564的Acer-Aspire7上使用Java 11.0.9启动CrudControllerTest(由Ashil在c:\Users\Ashil\Documents\Java+SpringBoot\crudRestApi中启动)
2020-12-29 08:36:04.792信息2564---[main]c.e.c.controller.CrudControllerTest:未设置活动配置文件,返回默认配置文件:默认
2020-12-29 08:36:06.607信息2564---[main]o.s.s.concurrent.ThreadPoolTaskExecutor:初始化ExecutorService'applicationTaskExecutor'
2020-12-29 08:36:07.103信息2564---[main]o.s.b.t.m.w.SpringBootMockServlet上下文:初始化Spring TestDispatcherServlet“”
2020-12-29 08:36:07.103信息2564---[main]o.s.t.web.servlet.TestDispatcherServlet:初始化servlet''
2020-12-29 08:36:07.106信息2564---[main]o.s.t.web.servlet.TestDispatcherServlet:在3毫秒内完成初始化
2020-12-29 08:36:07.155信息2564---[main]c.e.c.controller.CrudControllerTest:在2.943秒内启动CrudControllerTest(JVM运行5.294)
MockHttpServletRequest:
HTTP方法=PUT
请求URI=/customers/1
参数={}
Headers=[内容类型:“application/json;charset=UTF-8”,内容长度:“39”]
正文={“名称”:“测试”,“地址”:“测试”}
会话属性={}
处理程序:
Type=com.example.crudrestapi.controller.CrudController
Method=com.example.crudrestapi.controller.CrudController#updateCustomer(客户,长)
异步:
异步启动=错误
异步结果=空
已解决的异常:
Type=java.lang.IllegalStateException
ModelAndView:
视图名称=空
视图=空
模型=空
FlashMap:
属性=空
MockHttpServletResponse:
状态=404
错误消息=null
标题=[内容类型:“文本/普通;字符集=UTF-8”,内容长度:“18”]
内容类型=文本/普通;字符集=UTF-8
Body=未找到资源
转发的URL=null
重定向的URL=null
Cookies=[]
java.lang.AssertionError:状态应为:但为:
预计:200
实际:404
位于org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:59)
位于org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:122)
位于org.springframework.test.web.servlet.result.StatusResultMatchers.lambda$matcher$9(StatusResultMatchers.java:627)
位于org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:196)
位于com.example.crudrestapi.controller.CrudControllerTest.putApiTest(CrudControllerTest.java:85)
位于java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(本机方法)
位于java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
位于java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
位于java.base/java.lang.reflect.Method.invoke(Method.java:566)
位于org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:688)
位于org.junit.jupiter.engine.execution.MethodInvocation.procedure(MethodInvocation.java:60)
位于org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.Procedue(InvocationInterceptorChain.java:131)
位于org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:149)
位于org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:140)
位于org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:84)
位于org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)
位于org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)
位于org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.Procedue(InvocationInterceptorChain.java:106)
在org.junit.jupiter.engine.execution.InvocationInterceptorChain.procedure(InvocationInterceptorChain.java:64)上
位于org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45)
位于org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37)
位于org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104)
位于org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98)
位于org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$6(TestMethodTestDescriptor.java:210)
位于org.junit.platform.engine.support.hierarchy.ThrowableCollector.execute(ThrowableCollector.java:73)
位于org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:206)
位于org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:131)
位于org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:65)
位于org.junit.platform.engine.support.hierarchy.NodeTestTask.lambda$ExecuteCursive$5(NodeTestTask.java:139)
位于org.junit.platform.engine.support.hierarchy.ThrowableCollector.execute(ThrowableCollector.java:73)
位于org.junit.platform.engine.support.hierarchy.NodeTestTask.lambda$ExecuteCursive$7(NodeTestTask.java:129)
位于org.junit.platform.engine.support.hierarchy.Node.a