java - 如何在单元测试期间忽略一些 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"}, {"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
此测试的字段?从测试的角度来看,这并不重要,但其余的都很重要。
解决方案
您可以简单地将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")