【问题标题】:Junit Testing : org.junit.ComparisonFailureJunit 测试:org.junit.ComparisonFailure
【发布时间】:2018-06-15 10:58:25
【问题描述】:

我正在 Spring Boot 应用程序中学习 junit。我正在尝试为 Account 控制器 post 方法编写 JUnit 测试用例。我的帐户控制器取决于帐户服务方法,因此我使用mockito 进行模拟。我尝试编写如下所示的测试用例,但作为回应,我得到了空值。

谁能告诉我我在测试用例中做错了什么?

帐户控制器

@PutMapping("/saveAttributes")
    public ResponseEntity<Object> saveData(@RequestBody AccountMaintenanceSave saveObj){
        return accService.saveData(saveObj);
    }

AccountControllerTest

@RunWith(SpringRunner.class)
public class AccountControllerTest {

    private MockMvc mockMvc;

    @Mock
    private AccountService accountService;

    @InjectMocks
    private AccountController accountController;

    @Before
    public void setup() {
        mockMvc = MockMvcBuilders.standaloneSetup(accountController).build();
    }

    @Test
    public void btnSaveClickTest() throws Exception {

        AccountMaintenanceSave mockAccountMainSave = new AccountMaintenanceSave();
        mockAccountMainSave.setnAccountId(1);
        mockAccountMainSave.setsLocation("B");
        mockAccountMainSave.setnAccountCPCMappingid(3);
        mockAccountMainSave.setnDeptId(5);
        mockAccountMainSave.setsAcctDesc("abc");
        mockAccountMainSave.setsClientAcctId("2");
        mockAccountMainSave.setnInvestigatorId(4);

        String InputInJson = this.mapToJson(mockAccountMainSave);

        Mockito.when(accountService.saveData(mockAccountMainSave)) 
        .thenReturn(new ResponseEntity<>(mockAccountMainSave, HttpStatus.OK)); 

         MockHttpServletRequestBuilder  requestBuilder = MockMvcRequestBuilders 
        .put("/api.spacestudy.com/SpaceStudy/Admin/Account/saveAttributes") 
        .accept(MediaType.APPLICATION_JSON) 
        .content(InputInJson)
        .contentType(MediaType.APPLICATION_JSON);         

        MvcResult result = mockMvc.perform(requestBuilder).andReturn();

        MockHttpServletResponse response = result.getResponse();

        String outputInJson = response.getContentAsString();

        assertEquals(InputInJson, outputInJson);

        Mockito.verify(accountService).saveData(mockAccountMainSave);

        }   

        private String mapToJson(Object object) throws JsonProcessingException {

        ObjectMapper mapper = new ObjectMapper();
        return mapper.writeValueAsString(object);
        }
    }

堆栈跟踪

org.junit.ComparisonFailure: expected:<[{"nAccountId":1,"sClientAcctId":"2","sAcctDesc":"abc","sLocation":"B","nDeptId":5,"nAccountCPCMappingid":3,"nInvestigatorId":4}]> but was:<[]>
    at org.junit.Assert.assertEquals(Assert.java:115)
    at org.junit.Assert.assertEquals(Assert.java:144)
    at com.spacestudy.controller.AccountControllerTest.btnSaveClickTest(AccountControllerTest.java:78)
    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.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)

问题已解决 通过在 AccountMaintenanceSave 类中覆盖 equals()

@Override
    public boolean equals(Object mockAccountMainSave) {
        if (this == mockAccountMainSave) return true;
        if (mockAccountMainSave == null || getClass() != mockAccountMainSave.getClass()) return false;

        final AccountMaintenanceSave that = (AccountMaintenanceSave)mockAccountMainSave;

        if (!nAccountId.equals(that.nAccountId)) return false;
        if (!nAccountCPCMappingid.equals(that.nAccountCPCMappingid)) return false;
        if (nDeptId != that.nDeptId) return false;
        if (nInvestigatorId != that.nInvestigatorId) return false;
        if (sLocation != null ? !sLocation.equals(that.sLocation) : that.sLocation != null) return false;
        if (sAcctDesc != null ? !sAcctDesc.equals(that.sAcctDesc) : that.sAcctDesc != null) return false;
        return sClientAcctId != null ? sClientAcctId.equals(that.sClientAcctId) : that.sClientAcctId == null;
    }  

但我仍然对覆盖 equals() 后它的工作方式感到困惑。 assertEquals() 内部如何运作?

请给我一些澄清?

【问题讨论】:

  • 在standalonesetup之前在setup函数中使用MockitoAnnotations.initMocks(this)初始化你的模拟?并将@SpringBootTest(classes = {MockServletContext.class}) 放在您的测试类之上。
  • 我试过了。但没有出现同样的错误

标签: spring-boot junit mockito


【解决方案1】:

像这样初始化你的模拟

@Before
public void setup() {
    MockitoAnnotations.initMocks(this);
    mockMvc = MockMvcBuilders.standaloneSetup(accountController).build();
}

并像这样更改您的测试代码

MockHttpServletRequestBuilder  requestBuilder = MockMvcRequestBuilders 
    .put("/api.spacestudy.com/SpaceStudy/Admin/Account/saveAttributes") 
    .accept(MediaType.APPLICATION_JSON) 
    .content(InputInJson)
    .contentType(MediaType.APPLICATION_JSON);  


 mockMvc.perform(requestBuilder)
        .andExpect(status().isOk())
        .andExpect(content().json(InputInJson));

【讨论】:

  • org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.spacestudy.controller.AccountControllerTest': Unsatisfied dependency expressed through field 'mockMvc'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.test.web.servlet.MockMvc' available
  • 你有这个@SpringBootTest(classes = {MockServletContext.class})
  • 是的,我有
猜你喜欢
  • 2017-10-08
  • 1970-01-01
  • 2018-03-23
  • 1970-01-01
  • 2020-07-26
  • 2020-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多