关于spring:spring-JsonView解决循环对象引用遇到报错

3次阅读

共计 2086 个字符,预计需要花费 6 分钟才能阅读完成。

前言:

本周次要工夫用来写社区治理的后盾,遇到的次要问题就是对于初期对于模块化了解不够粗浅。导致本人一个简略的模块被一直的放大。

遇到问题:

问题形容:

根据前台 MockApi 来进行单元测试,其中返回后盾的返回数据包含:县、乡镇、社区、小区

县:乡镇:社区:小区 均为一对多的关系。

结构返回数据代码:

public static County getOneCounty() {logger.debug("结构返回数据县")
    County county = new County();
    county.setId(new Random().nextLong());
    county.setName(new RandomString().nextString());
    logger.debug("获取乡镇");
    logger.debug("乡镇中有社区 List,社区中有小区 List")
    Town town = TownControllerTest.getOneTown();
    county.getTowns().add(town);

    return county;
  }

测试代码

@Test
  void getCounty() throws Exception {
    String url = baseUrl + "/county";

    County county = getOneCounty();

    Mockito.doReturn(county).when(this.systemService).getCounty();

    this.mockMvc.perform(MockMvcRequestBuilders.get(url))
        .andExpect(MockMvcResultMatchers.jsonPath("$.id").value(county.getId()))
        .andExpect(MockMvcResultMatchers.jsonPath("$.name").value(county.getName()))
        .andExpect(MockMvcResultMatchers.jsonPath("$.towns[0].id").exists())
        .andExpect(MockMvcResultMatchers.jsonPath("$.towns[0].communities[0].id").exists())
        .andExpect(MockMvcResultMatchers.jsonPath("$.towns[0].communities[0].villages[0].id").exists())
        .andExpect(MockMvcResultMatchers.status().isOk());
  }

报错

through reference chain: club.yunzhi.smartcommunity.entity.Community["town"]->club.yunzhi.smartcommunity.entity.Town["communities"]->java.util.ArrayList[0]->club.yunzhi.smartcommunity.entity.Community["town"]->club.yunzhi.smartcommunity.entity.Town["communities"]->java.util.ArrayList[0]->club.yunzhi.smartcommunity.entity.Community["town"]->club.yunzhi.smartcommunity.entity.Town["communities"]->java.util.ArrayList[0]->club.yunzhi.smartcommunity.entity.Community["town"]->club.yunzhi.smartcommunity.entity.Town["communities"]......

解决:

看谬误提醒

依据报错提醒能够看出是始终在 town 和 community 循环了:town 中蕴含 community,每个 community 又蕴含一个 town,如此一直的获取。

查看返回数据

论断:猜测是我在 town 的 community 中设置了 town 吗?

管他呢,删了试试

再报错:

community.village[0] 不存在!

打断点测试


明明有 village[0] 啊

忽然想到 JsonView

查看 C 层代码:

public class GetAllCountyJsonView implements 
      County.TownJsonView, 
      Town.CommunityJsonView, 
      Community.TownJsonView {}

豁然开朗:County->town->community->town->community->town…..

总结:

感激单元测试,因为有了单元测试才可能在只有后盾的状况下排查出本人后盾的 BUG,同时也对于 JsonView 加深了了解

版权申明

本文作者:河北工业大学梦云智开发团队 – 郝泽龙

正文完
 0