Jsonpath возвращает NULL для вложенных объектов JSON в Spring Boot Test - PullRequest
0 голосов
/ 09 октября 2019

В тесте Spring Boot мне нужно сравнить / сопоставить результат вызова контроллера покоя с ранее созданной сущностью Java с вложенными объектами.

Это сущность Java:

@Entity
@Table(name="Referente")
public class Referente {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "idReferente", updatable = false, nullable = false)
    private Integer idReferente;

    @ManyToOne
    @JoinColumn(name="idCliente")
    private Cliente cliente;

    @Column(name = "cognomeReferente")
    private String cognomeReferente;

...

У вложенного объекта Cliente есть еще один вложенный объект с именем Agente:

@Entity
@Table(name="Cliente")
public class Cliente {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "idCliente", updatable = false, nullable = false)
    private Integer idCliente;

    @Column(name = "nominativo")
    private String nominativo;

    @Column(name = "dataProssimoContatto")
    private LocalDateTime dataProssimoContatto;

    @ManyToOne
    @JoinColumn(name = "idAgentePrimoContatto")
    private Agente agentePrimoContatto;
@Entity
@Table(name="Agente")
public class Agente {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "idAgente", updatable = false, nullable = false)
    private Integer idAgente;

    @Column(name = "nome")
    private String nome;

    @Column(name = "cognome")
    private String cognome;

    @Column(name = "telefono")
    private String telefono;

Это метод теста:

@Test
public void getAllReferente_Test() throws Exception {

 initializeData();

 mvc.perform(get("/referente").contentType(MediaType.APPLICATION_JSON))

.andExpect(status().isOk())
.andExpect(jsonPath("$[0].idReferente").value(referente1.getIdReferente()))
// Here the error 
.andExpect(jsonPath("$[0].cliente").value(referente1.getCliente()))
.andExpect(jsonPath("$[0].cognomeReferente").value(referente1.getCognomeReferente()));

Когда я запускаю метод теста Iполучить следующее сообщение об ошибке:

java.lang.AssertionError: JSON path "$[0].cliente" 

expected:<Cliente [idCliente=1, nominativo=NOMINATIVOCLIENTE1, dataProssimoContatto=2019-10-16T16:19:59.111111111, agentePrimoContatto=Agente [idAgente=1, nome=NOME1, cognome=COGNOME1, telefono=11111, mail=MAIL1, isRemovibile=null], dataPrimoContatto=2019-07-20, agenteInEssere=Agente [idAgente=1, nome=NOME1, cognome=COGNOME1, telefono=11111, mail=MAIL1, isRemovibile=null], consensoPrivacy=true, indirizzo=VIA INDIRIZZO1, cap=11111, citta=CITTA1, provincia=PR, settoreMerceologico=SettoreMerceologico [idSettoreMerceologico=1, descrizione=SETTOREMERCEOLOGIOCO], statoCliente=StatoCliente [idStatoCliente=1, descrizione=NUOVO]]> 

but was:<null>

Но в другом тестовом случае (где у меня нет вложенных объектов) все работает нормально:

@Test
public void getAllCliente2Call() throws Exception {

  initializeData();
  mvc.perform(get("/cliente/data/" + dataProssimoContatto).contentType(MediaType.APPLICATION_JSON))

.andExpect(status().isOk())
.andExpect(jsonPath("$").isNotEmpty())
.andExpect(jsonPath("$", hasSize(2)))
.andExpect(jsonPath("$[0].idCliente").value(cliente2.getIdCliente()))
.andExpect(jsonPath("$[0].nominativo").value(cliente2.getNominativo())
.andExpect(jsonPath("$[0].dataProssimoContatto",is(cliente2.getDataProssimoContatto().toString())))
// Here works fine (not have nested objects in agente)
.andExpect(jsonPath("$[0].agentePrimoContatto").value(cliente2.getAgentePrimoContatto()));

Почему в первом тестовом примере JSONпуть "$ [0] .cliente" вернуть ноль? Какой лучший способ сделать это?

1 Ответ

0 голосов
/ 10 октября 2019

решено

Я решил, следуя этому другому потоку:

Сопоставление объекта в JSON с jsonpath в Spring Boot Test

Здесь код:

private <T> T asParsedJson(Object obj) throws JsonProcessingException {
    String json = new ObjectMapper().writeValueAsString(obj);
    return JsonPath.read(json, "$");
}

Тогда

.andExpect(jsonPath("$[0].cliente").value(equalTo(asParsedJson(referente1.getCliente()))))
...