预期的例外JUNIT

时间:2013-04-21 19:34:43

标签: java exception testing junit4 expected-exception

我想在DB中添加一个对象,而不是检查对象是否已经存在,所以我们不能添加它两次。我用JUNIT测试它:

@org.junit.Test (expected = ExistingProduct.class)
public void AddExisting() 
{

    Register aRegister = new Register();
    Product aProduct = new Product();
    aProduct.setPIN("079400027252"); 

    aRegister.AddProduct(aProduct);


    Product sameProduct = new Product();
    sameProduct.setPIN("079400027252");

    aRegister.AddProduct(sameProduct); //this throw the exception


    aRegister.deleteProduct("079400027252"); //CAN'T REACH HERE
}

问题是我无法删除产品,因为之前调用的指令会抛出异常,从而结束测试。

2 个答案:

答案 0 :(得分:0)

好吧,我有点想办法...... 我将@Before方法称为从BD中删除所有内容并将其恢复为默认值

答案 1 :(得分:0)

也许像这样解决这个问题。 谢尔盖·别列佐夫斯基(Sergey Berezovskiy)的https://stackoverflow.com/a/20494165/4296891更多内容

public void AddExisting() 
    {

        Register aRegister = new Register();
        Product aProduct = new Product();
        aProduct.setPIN("079400027252"); 

        aRegister.AddProduct(aProduct);


        Product sameProduct = new Product();
        sameProduct.setPIN("079400027252");
        try
        {
            aRegister.AddProduct(sameProduct); //this throw the exception
            assertEquals("Can't add it twice exception has been excepted." ,true, false);
        }
        catch(ExistingProduct exception)
        {        
            // exception
        }

        aRegister.deleteProduct("079400027252"); //CAN'T REACH HERE
    }