AssertionError: No value at JSON path, but value exists in valid JSON response

AssertionError: No value at JSON path, but value exists in valid JSON response

我看到这里、论坛上提供了很多解决方案,还有一个问题指南(提供here),但是none其中帮助了我...

我尽量保持我的代码清晰,所以我决定创建许多测试 类 包括测试项目,例如:

@Getter
@Setter
public class SalesTaskTestItem {

    public static SalesTask buildTestItem(){

        List<ContactPerson> contactPersonTestItemList = new ArrayList<>();
        contactPersonTestItemList.add(ContactPersonTestItem.buildTestItem());

        List<SalesMan> supportingSalesTeamList = new ArrayList<>();

        List<Product> discussedProductsTestList = new ArrayList<>();
        discussedProductsTestList.add(ProductTestItem.buildTestItem());

        List<SalesTaskProgress> progressTestList = new ArrayList<>();
        progressTestList.add(SalesTaskProgressTestItem.buildTestItemNo1());
        progressTestList.add(SalesTaskProgressTestItem.buildTestItemNo2());
        progressTestList.add(SalesTaskProgressTestItem.buildTestItemNo3());

        List<Offer> alreadySentOffersTestList = new ArrayList<>();
        alreadySentOffersTestList.add(OfferTestItem.buildTestItem());

        List<AssignedTaskDocument> assignedTaskDocumentsTestList = new ArrayList<>();
        assignedTaskDocumentsTestList.add(AssignedTaskDocumentTestItem.buildTestItem());

        List<InternalProcedureDocument> internalProceduresDocumentsTestList = new ArrayList<>();
        internalProceduresDocumentsTestList.add(InternalProcedureDocumentTestItem.buildTestItem());


        SalesTask testItem = new SalesTask();
        testItem.setId(1L);
        testItem.setVersion(1);
        testItem.setTaskEstablishedDate(DateFormatter.fromStringToDate("10-12-2020T09:12:45"));
        testItem.setLastProgressDate(DateFormatter.fromStringToDate("10-12-2020T09:30:56"));
        testItem.setCompany(CompanyTestItem.buildTestItem());
        testItem.setContactPersonsList(contactPersonTestItemList);
        testItem.setMainSalesMan(SalesManTestItem.buildTestItemNo1());
        testItem.setSupportingSalesTeam(supportingSalesTeamList);
        testItem.setDiscussedProducts(discussedProductsTestList);
        testItem.setProgressList(progressTestList);
        testItem.setCurrentTaskValue(BigDecimal.valueOf(250000));
        testItem.setChanceOfPositiveFinishingTask(0.45);
        testItem.setEstimatedDateOfFinishingTask(DateFormatter.fromStringToDate("30-12-2020T13:00:00"));
        testItem.setAlreadySentOffersList(alreadySentOffersTestList);
        testItem.setAssignedTaskDocumentsList(assignedTaskDocumentsTestList);
        testItem.setInternalProceduresDocumentsList(internalProceduresDocumentsTestList);
        return testItem;
    }

}

我的测试用例是:

package com.jmdev.storycrm.controllers;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.jmdev.storycrm.domain.salesTask.SalesTask;
import com.jmdev.storycrm.services.SalesTaskService;
import com.jmdev.storycrm.testDomainItems.salesTask.SalesTaskTestItem;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
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.context.junit.jupiter.SpringExtension;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultActions;

import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

@ExtendWith(SpringExtension.class)
@WebMvcTest

public class SalesTaskControllerTest {

    @Autowired
    MockMvc mockMvc;

    @MockBean
    private SalesTaskService salesTaskService;


    @Test
    public void createNewSalesTask(){

        SalesTask newSalesTask = new SalesTask();
        newSalesTask = SalesTaskTestItem.buildTestItem();

        when(salesTaskService.save(any(SalesTask.class))).thenReturn(newSalesTask);

        ObjectMapper objectMapper = new ObjectMapper().registerModule(new JavaTimeModule());

        try {
            String newSalesTaskJSON = objectMapper.writeValueAsString(newSalesTask);

            ResultActions resultActions = mockMvc.perform(
                    post("/salesTask")
                    .contentType(MediaType.APPLICATION_JSON)
                    .content(newSalesTaskJSON)
            );

            resultActions.andExpect(status().isCreated())
                    .andDo(print())
                    .andExpect(content().contentType("application/json"))
                    .andExpect(jsonPath("$.id").value(1L))
                    .andExpect(jsonPath("$.version").value(1))
                    .andExpect(jsonPath("$.taskEstablishedDate").value(SalesTaskTestItem.buildTestItem().getTaskEstablishedDate().toString()))
                    .andExpect(jsonPath("$.lastProgressDate").value(SalesTaskTestItem.buildTestItem().getLastProgressDate().toString()))
                    .andExpect(jsonPath("$.company").value(SalesTaskTestItem.buildTestItem().getCompany()))
                    .andExpect(jsonPath("$.contactPersonsList").value(SalesTaskTestItem.buildTestItem().getContactPersonsList()))
                    .andExpect(jsonPath("$.mainSalesMan").value(SalesTaskTestItem.buildTestItem().getMainSalesMan()))
                    .andExpect(jsonPath("$.supportingSalesTeam").value(SalesTaskTestItem.buildTestItem().getSupportingSalesTeam()))
                    .andExpect(jsonPath("$.discussedProducts").value(SalesTaskTestItem.buildTestItem().getDiscussedProducts()))
                    .andExpect(jsonPath("$.progressList").value(SalesTaskTestItem.buildTestItem().getProgressList()))
                    .andExpect(jsonPath("$.currentTaskValue").value(SalesTaskTestItem.buildTestItem().getCurrentTaskValue()))
                    .andExpect(jsonPath("$.chanceOfPositiveFinishingTask").value(SalesTaskTestItem.buildTestItem().getChanceOfPositiveFinishingTask()))
                    .andExpect(jsonPath("$.estimatedDateOfFinishingTask").value(SalesTaskTestItem.buildTestItem().getEstimatedDateOfFinishingTask()))
                    .andExpect(jsonPath("$.alreadySentOffersList").value(SalesTaskTestItem.buildTestItem().getAlreadySentOffersList()))
                    .andExpect(jsonPath("$.assignedTaskDocumentsList").value(SalesTaskTestItem.buildTestItem().getAssignedTaskDocumentsList()))
                    .andExpect(jsonPath("$.internalProceduresDocumentsList").value(SalesTaskTestItem.buildTestItem().getInternalProceduresDocumentsList()));

        } catch (Exception e) {
            e.printStackTrace();
        }

    }


}

我在堆栈跟踪中看到我的 MockHttpServletResponse,我可以在其中找到 "taskEstablishedDate":"2020-12-10T09:12:45.000+00:00"。此外,如果我复制此响应的整个主体并将其传递到 https://jsonformatter.curiousconcept.com/,则可以顺利通过验证。

MockHttpServletResponse:
           Status = 201
    Error message = null
          Headers = [Content-Type:"application/json"]
     Content type = application/json
             Body = {"id":1,"version":1,"taskEstablishedDate":"2020-12-10T09:12:45.000+00:00","lastProgressDate":"2020-12-10T09:30:56.000+00:00", (...) }
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

但我得到 java.lang.AssertionError:JSON 路径“$.taskEstablishedDate”.

没有值

真不知道怎么回事。有人可以帮忙吗?

编辑: 我实施了 SSK 建议,现在日期和时间已经过去了。为了测试下一个 JSON 值,作为我的应用程序的对象提供,我将 GSON 实现为覆盖 toString() 方法:

package com.jmdev.storycrm.domain.company;

import com.jmdev.storycrm.utils.JSONFormatter;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
@Getter
@Setter
public class Company {

    @Id
    private Long id;
    private String name;
    private Long nipNumber;
    private Address address;

    @Override
    public String toString() {
        return JSONFormatter.useGSON(this);
    }   
}

使用了 toString() 格式化程序:

package com.jmdev.storycrm.utils;

public class JSONFormatter {

    public static String useGSON(Object object){
        return new com.google.gson.Gson().toJson(object);
    }
}

但是我得到 java.lang.AssertionError 两个完全相同的值...

java.lang.AssertionError: JSON path "$.company" (...)
Expected :{"id":1,"name":"TestCompanyName","nipNumber":345353534354335,"address":{"id":1,"voivodeship":"Region name","postalCode":"99-000","city":"My City name","street":"Main Street name","fullBiuldingNumber":"100","flatNumber":1}}
Actual   :{"id":1,"name":"TestCompanyName","nipNumber":345353534354335,"address":{"id":1,"voivodeship":"Region name","postalCode":"99-000","city":"My City name","street":"Main Street name","fullBiuldingNumber":"100","flatNumber":1}} 

您需要使用 ObjectMapper 注册您的 JavaTimeModule
您可以如下所示注册 JavaTimeModule。

ObjectMapper objectMapper = new ObjectMapper().registerModule(new JavaTimeModule());

然后使用相同的 objectMapper 创建 json 字符串

String newSalesTaskJSON = objectMapper.writeValueAsString(newSalesTask);

JavaTimeModule 来自 com.fasterxml.jackson.datatype.jsr310.JavaTimeModule

此外,您需要将 .toString() 添加到 .andExpect() 中的日期值,如下所示

.andExpect(jsonPath("$.taskEstablishedDate").value(SalesTaskTestItem.buildTestItem().getTaskEstablishedDate().toString()))
.andExpect(jsonPath("$.lastProgressDate").value(SalesTaskTestItem.buildTestItem().getLastProgressDate().toString()))
.andExpect(jsonPath("$.estimatedDateOfFinishingTask").value(SalesTaskTestItem.buildTestItem().getEstimatedDateOfFinishingTask().toString()))