首页 > 解决方案 > 当 .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);
        }
    }

标签: javaspringjunit

解决方案


推荐阅读