gpt4 book ai didi

java - 如何为内部包含 "this"的方法编写Junit测试

转载 作者:行者123 更新时间:2023-12-01 17:40:49 24 4
gpt4 key购买 nike

我有以下方法:

public class Store {

@Autowired
private List<Products> products;

public Products find(final String id) {
for (final Products product : this.products) {
if (product.getId().equalsIgnoreCase(id)) {
return product;
}
}
return null;
}
}

如何为这个方法编写Junit?如果我这样写,就会发生 NullPointerException。

@SpringBootTest
@ContextConfiguration(locations = {"classpath*:beans.xml"})
@RunWith(SpringRunner.class)
public class StoreTest {

@SuppressWarnings("unused")
@Autowired
private List<Products> products;

@Test
public void find() {
Store store = new Store();
Products product = new Products();
product = store.find("1");
final String result = product.getName();
Assert.assertEquals("it should be equal", "Milk", result);
}

}

提前致谢!

最佳答案

您没有将产品对象或产品列表添加到商店中,因此 find 返回 null 是有意义的。

您可以做的是将产品添加到商店,然后检查产​​品的结果是否为空,如果是则断言出了问题。您还可以检查您添加的产品是否是您正在查找的产品。

@Test
public void find() {
final Store store = new Store();

final List<Products> products = new ArrayList<>();

final Products product1 = new Products("Cucumber", "The best cucmber", 500, "1");
final Products product2 = new Products("Cherry", "The best Cherry", 1000, "2");
Products product = new Products();

products.add(product1);
products.add(product2);

Products found = store.find("1");

Assert.assertNotNull(product); // check if result is null

Assert.assertEquals(product, found); // check if what you added is your result
}

关于java - 如何为内部包含 "this"的方法编写Junit测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60951074/

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