java - 当 .deleteAll() 方法在其之前执行时,以下测试失败
问题描述
我有一个 JUnit 测试来检查服务是否正常工作。在每次测试之后或之前我想清理数据库表,所以我执行repository.deleteAll();
但测试失败。没有它,测试工作正常,但它需要row
以前的测试。当我在 void 测试方法中执行 deleteAll() 失败时,它失败了,但是当我添加synchronized(this) { repository.deleteAll();}
测试时是绿色的。这里可能有什么问题?同样奇怪的是,当我不执行 deleteAll() 并运行所有测试时,一切都是绿色的,但它不应该是绿色的,因为在最后一次测试中我正在检查产品的数量。如果产品名称在数据库中,则取他的数量。
public class ShoppingCartServiceTest extends DatabaseConnectionTest {
@Autowired
private ProductRepository productRepository;
@Autowired
private ProductServiceImpl productService;
@Autowired
private ShoppingCartService shoppingCartService;
@Before
public void setUp() {
productRepository.deleteAll();
}
@Test
public void shouldAddProduct() {
Product product = new Product(1L,"Blue Jeans", "Trend Blue Jeans",
ProductCategory.CLOTHES, 5, 30.00);
shoppingCartService.addProduct(product);
assertNotNull(productService.findById(product.getId()));
}
@Test
public void shouldIncreaseEntityOfProductWhenAlreadyExists() {
Product product = new Product(1L, "White Shorts", "Extra White Shorts",
ProductCategory.CLOTHES, 3, 15.00);
shoppingCartService.addProduct(product);
Product productTwo = new Product(2L, "White Shorts", "Extra White Shorts",
ProductCategory.CLOTHES, 5, 15.00);
shoppingCartService.addProduct(productTwo);
assertNotNull(productService.findById(product.getId()));
assertNull(productService.findById(productTwo.getId()));
Integer expectedQuantity = product.getQuantity() + productTwo.getQuantity();
assertEquals(expectedQuantity, productService.findById(product.getId()).getQuantity());
}
}
@Override
public void addProduct(Product product) {
if (product == null)
return;
// if the product is already added, then increase the quantity
// if not the add it as new product
Product actualProduct = productRepository.findByName(product.getName());
if (actualProduct != null) {
int quantity = product.getQuantity() + actualProduct.getQuantity();
actualProduct.setQuantity(quantity);
productRepository.save(actualProduct);
}
else {
productRepository.save(product);
}
}
解决方案
推荐阅读
- python - 在 Django UpdateView 中覆盖 get() 方法会给出“str”没有属性获取错误
- angular - 反应形式的总和数组
- vba - 如何搜索字符串并突出显示相邻的单词?
- java - Netbeans Maven 项目中 ResourceBundle 的 Bundle 类路径无效
- arrays - 列表中总和的练习
- javascript - 动态插入到 DOM 后,样式不会应用于 HTML 元素 - Angular
- android - 我想要使用 android-studio 在 android 中以某个数字开头的按钮的代码
- pandas - 使用多个键转换熊猫数据框
- animation - 如何在 adobe animate 2021 中扭曲视频?
- c - C 调用具有空声明 arglist 的函数,使用 args 定义