【问题标题】:How can I ignore some JSON and object properties during unit testing?如何在单元测试期间忽略一些 JSON 和对象属性?
【发布时间】:2020-08-12 08:44:46
【问题描述】:

我有一种方法可以将旧的 JSON 结构迁移到我想测试的新结构,但是我想忽略一个随机生成的属性 (UUID)。

对象的有趣部分如下所示:

val expected = FooterContainer(id = UUID.fromString("11914145-9775-4675-9c65-54bbd369fb2c"), title = null, flowType=ContainerType.ROWS, elements=listOf() //the rest is not important.

要转换的 JSON 看起来与此对象完全不同,但这是该方法的目的 - 将其转换为新模型。

val json = """[{"type": "list", "items": [{"link": "www.something.com", "type": "link", "label": "Some label"},
            {"type": "text", "label": "Another label"}, {"type": "text", "label": "Other label"},
            {"type": "text", "label": "yet another label"}, {"type": "text", "label": "info@something.com"}]

等等。

以下代码按预期工作:

val gson: JsonElement = Gson().fromJson(json, JsonElement::class.java)

    // when
    val converted = with(ClientDataRepository()) {
        gson.readFooter()
    }

直到我不得不在FooterContainer 对象中引入一个新字段,即val id: UUID

readFooter() 方法正在随机生成UUID,这是预期的行为。

但现在,我不能只为预期的类分配一个随机(或硬编码,如上面的示例代码)UUID,这是合乎逻辑的 - 两个随机生成的 UUID 永远不会相同。

当我运行测试时,我显然得到:

Expected :FooterContainer(id=11914145-9775-4675-9c65-54bbd369fb2c,
Actual   :FooterContainer(id=7ba39ad0-1412-4fda-a827-0241916f8558,

现在,是否有可能忽略此测试的 id 字段?从测试的角度来看,这并不重要,但其余的都很重要。

【问题讨论】:

    标签: java json unit-testing kotlin junit4


    【解决方案1】:

    您可以简单地将id 字段从actual 对象复制到expected

    val converted = with(ClientDataRepository()) {
        gson.readFooter()
    }
    
    val expected = FooterContainer(id = converted.id, title = null, flowType=ContainerType.ROWS, elements=listOf()) //the rest is not important.
    Assertions.assertThat(converted).isEqualTo(expected);
    

    如果你使用assertJ,有一个简单的解决方案:

    Assertions.assertThat(converted).isEqualToIgnoringGivenFields(expected, "id")
    

    【讨论】:

      【解决方案2】:

      您可以使用支持忽略键的 json-assert (https://github.com/skyscreamer/JSONassert) 之类的东西 - https://stackoverflow.com/a/44328139/4473822

      【讨论】:

        【解决方案3】:

        试试JsonUnit。在这种情况下,您可以通过以下方式修改您的代码:

        assertThatJson("{\"id\":${json-unit.ignore}}").isEqualTo("{\"id\": 11914145-9775-4675-9c65-54bbd369fb2c}");
        

        【讨论】:

          猜你喜欢
          • 2017-11-27
          • 2018-06-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-11-23
          • 1970-01-01
          相关资源
          最近更新 更多