在单元测试期间,如何忽略某些JSON和对象属性?

问题描述

我有一种方法可以将旧的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"},"label": "Other label"},"label": "yet another label"},"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字段?从测试的角度来看这并不重要,但其余的才是重要的。

解决方法

您只需将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")
,

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

,

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

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

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...