0

我想在数据库中添加一个对象而不是检查该对象是否已经存在所以我们不能添加它两次。我用 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
}

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

4

2 回答 2

0

好吧,我有点想出一些东西...我调用@Before方法女巫从BD中删除所有内容并放回默认值

于 2013-04-21T20:13:21.833 回答
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
    }
于 2015-02-08T23:16:19.010 回答