Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/13.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 MockMvc测试POST请求返回错误:实际调用具有不同的参数:_Java_Spring_Spring Boot_Spring Mvc_Mockmvc - Fatal编程技术网

Java MockMvc测试POST请求返回错误:实际调用具有不同的参数:

Java MockMvc测试POST请求返回错误:实际调用具有不同的参数:,java,spring,spring-boot,spring-mvc,mockmvc,Java,Spring,Spring Boot,Spring Mvc,Mockmvc,我是后端测试新手,我正在用MockMvc测试我的spring boot应用程序。但是,当我想测试我的Post请求时,我在使用时遇到了标题中提到的错误 verify(userService,atLeastOnce()).addUser(user1); 错误日志如下所示: {"id":1,"name":"Burakhan Aksoy","email":"burak@burak.com","

我是后端测试新手,我正在用MockMvc测试我的spring boot应用程序。但是,当我想测试我的Post请求时,我在使用时遇到了标题中提到的错误

verify(userService,atLeastOnce()).addUser(user1);
错误日志如下所示:

{"id":1,"name":"Burakhan Aksoy","email":"burak@burak.com","gender":"Male","phoneNumber":"12321"}

MockHttpServletRequest:
      HTTP Method = POST
      Request URI = /users
       Parameters = {}
          Headers = [Content-Type:"application/json;charset=UTF-8", Content-Length:"96"]
             Body = {"id":1,"name":"Burakhan Aksoy","email":"burak@burak.com","gender":"Male","phoneNumber":"12321"}
    Session Attrs = {}

Handler:
             Type = io.thebman.restapitesting.controllers.UserController
           Method = io.thebman.restapitesting.controllers.UserController#addUser(User)

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = null

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

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 201
    Error message = null
          Headers = [Content-Type:"application/json"]
     Content type = application/json
             Body = {"id":1,"name":"Burakhan Aksoy","email":"burak@burak.com","gender":"Male","phoneNumber":"12321"}
    Forwarded URL = null
   Redirected URL = null
          Cookies = []


Argument(s) are different! Wanted:
io.thebman.restapitesting.service.UserService#0 bean.addUser(
    io.thebman.restapitesting.view.User@1b5a1d85
);
-> at io.thebman.restapitesting.UserControllerTest.postUserThenValidateUserAddedSuccessfully(UserControllerTest.java:119)
Actual invocations have different arguments:
io.thebman.restapitesting.service.UserService#0 bean.addUser(
    io.thebman.restapitesting.view.User@31e130bf
);
-> at io.thebman.restapitesting.controllers.UserController.addUser(UserController.java:32)

Comparison Failure: 
<Click to see difference>

Argument(s) are different! Wanted:
io.thebman.restapitesting.service.UserService#0 bean.addUser(
    io.thebman.restapitesting.view.User@1b5a1d85
);
-> at io.thebman.restapitesting.UserControllerTest.postUserThenValidateUserAddedSuccessfully(UserControllerTest.java:119)
Actual invocations have different arguments:
io.thebman.restapitesting.service.UserService#0 bean.addUser(
    io.thebman.restapitesting.view.User@31e130bf
);
-> at io.thebman.restapitesting.controllers.UserController.addUser(UserController.java:32)

    at io.thebman.restapitesting.UserControllerTest.postUserThenValidateUserAddedSuccessfully(UserControllerTest.java:119)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    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.util.ArrayList.forEach(ArrayList.java:1259)
    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.util.ArrayList.forEach(ArrayList.java:1259)
    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)

package io.thebman.restapitesting.controllers;

import io.thebman.restapitesting.service.UserService;
import io.thebman.restapitesting.view.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/users/{id}")
    public User getUserById(@PathVariable int id){

        return userService.getUser(id);
    }

    @RequestMapping("/users")
    public List<User> getUsers(){
        return userService.getUsers();
    }

    @PostMapping("/users")
    public @ResponseBody
    ResponseEntity<User> addUser(@RequestBody User user){
        return new ResponseEntity<User>(userService.addUser(user), HttpStatus.CREATED);
    }
}
package io.thebman.restapitesting;

import com.fasterxml.jackson.databind.ObjectMapper;
import io.thebman.restapitesting.controllers.UserController;
import io.thebman.restapitesting.service.UserService;
import io.thebman.restapitesting.view.User;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentMatchers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultMatcher;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.ContentResultMatchers;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import static org.hamcrest.MatcherAssert.assertThat;

import static org.hamcrest.Matchers.*;

import java.util.Arrays;
import java.util.List;

import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

@WebMvcTest(UserController.class)
public class UserControllerTest {
    @Autowired
    private UserController userController;

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private UserService userService;

    //Test /users (POST)
    @Test
    public void postUserThenValidateUserAddedSuccessfully() throws Exception {
        User user1 =new User(1,"Burakhan Aksoy",
                "burak@burak.com","Male",
                "12321");

        when(userService.addUser(any(User.class))).thenReturn(user1);

        //Start mocking http request
         mockMvc.perform(MockMvcRequestBuilders.post("/users")
                .contentType(MediaType.APPLICATION_JSON)
                .content(asJsonString(new User(1,"Burakhan Aksoy",
                        "burak@burak.com","Male",
                        "12321"))))
                .andExpect(status().isCreated())
                .andExpect(jsonPath("$.id").exists())
                .andExpect(jsonPath("$.name").value("Burakhan Aksoy"))
                 .andExpect(jsonPath("$.email").value("burak@burak.com"))
                 .andExpect(jsonPath("$.gender").value("Male"))
                 .andExpect(jsonPath("$.phoneNumber").value("12321"));

        verify(userService,atLeastOnce()).addUser(user1);
//        verifyNoMoreInteractions(userService);
    }
    public static String asJsonString(final Object obj) {
        try {
            final ObjectMapper mapper = new ObjectMapper();
            final String jsonContent = mapper.writeValueAsString(obj);
            System.out.println(jsonContent);
            return jsonContent;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
谢谢你的帮助


最好的方法是,尝试重载用户类中的默认
hashCode()
equals()
方法

在您的场景中,它考虑两个不同的对象,并基于默认对象的方法(检查地址)进行比较

编辑: 作为这个测试用例的一部分,您只需要重写
equals()
方法。但是如果无法覆盖
hashCode()
,将来使用任何
Hash
相关集合(如
HashTable、HashMap等)时可能会遇到问题。


有关更多详细信息,请参阅:

您的
用户
类是否有正确实现的
equals
方法?在
verify
调用中,您希望它接收参数
user1
,但控制器的处理程序方法实际上是使用从JSON内容反序列化的新
User
对象调用
addUser
。除非有合适的
equals
方法来比较它们,否则它们永远不会相等(iirc)。谢谢你的回答。我没有相等的方法。我如何实现它?作为后续问题,即使我重写了equals方法并确保它们确实相同,我如何在测试用例中使用它?我的意思是我仍将使用verify(userService,atleastone()).addUser(user)。那么,重写equals方法并确保user1和user是相等的如何帮助这个测试用例通过呢?
equals方法在幕后为您所用。Mockito将比较您的
verify()
与您的
@PostMapping
方法中实际传递给
addUser
的内容。