gpt4 book ai didi

java - 在断言之前测试被测试对象是否不为空的正确方法

转载 作者:行者123 更新时间:2023-12-01 20:08:50 25 4
gpt4 key购买 nike

我编写了我的第一个测试,我希望你问我的测试是否正确。我需要测试更新方法后是否更新了某个对象,所以这是我的测试结构:

@Test
public void myTest {
// init myObj variable which I want test
// myObjService is my service for my object which I've initialized in @Before tagged function
MyObj myObj = myObjService.getById(465);

// test if that variable is initialized, and it is not null
Assert.assertNotNull(myObj);

// update some properties of myObj
myObj.setX(...);
myObj.setY(...);
...

// call update function which update obj in collection by Id of object
myObjService.update(myObj);

// get object with same id which should be with updated properties
MyObj myUpdatedObj = myObjService.getById(465);

// test that properties
Assert.assertEquals(myObj.getX(), myUpdatedObj.getX());
Assert.assertEquals(myObj.getY(), myUpdatedObj.getY());
...
}

该过程正确还是我应该编辑一些内容?

最佳答案

为什么需要空检查?您寻求什么好处?因为:

  1. 您可以通过在测试本身中准备所有测试数据来显式控制 null 是否可能。
  2. 如果由于某种原因您无法执行此操作 - 您仍然需要从测试中清楚地说明失败时发生的情况。您可以通过堆栈跟踪中的 NPE 轻松找到这一点。所以我不会用额外的行来记录测试。特别是考虑到在您的情况下,由于测试设置中的错误更有可能发生 null。

我的建议是准备测试本身的所有数据:

public void updatesAllFieldsOfDog() {
//creates object with random values
Dog original = dao.createDog(Dog.random());
//create new object with random fields and set the ID to the original
//which effectively means - original object with all fields updated
Dog updated = Dog.random().setId(original.getId());
dao.updateDog(updated);
Dog fromDb = dao.getDog(original.getId());
//Method from Unitils that compares all the fields
assertReflectionEquals(updated, fromDb);
}

类似的测试可以找到here如果您对详细信息感兴趣。

关于java - 在断言之前测试被测试对象是否不为空的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47023993/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com