简体   繁体   English

单元测试在预期的InvalidOperationException上失败

[英]Unit Test fails on expected InvalidOperationException

I have written a unit test to test the some SQL operations in my application. 我已经编写了单元测试来测试应用程序中的一些SQL操作。 Here is the test: 这是测试:

[TestMethod]
[ExpectedExceptionAttribute(typeof(InvalidOperationException))]
public void ExecuteSQL_CommandInvalidSyntax_ThrowsException()
{
    var result = TestSqlHandler.ExecuteSQL(new List<int>
    {
        1, 2, 3, 4
    }, "Invalid command text");
}

Method in question: 有问题的方法:

public static Exception ExecuteSQL(List<int> walletList, string command)
{
    try
    {
        using (var conn = new SqlConnection("Omitted"))
        {
            if (conn.State == ConnectionState.Open)
                conn.Close();


            string sql = command;
            using (var cmd = new SqlCommand(sql, conn))
            {
                conn.Open();
                foreach (int row in walletList)
                {
                    cmd.Parameters.AddWithValue("@par1", row.ToString());
                    cmd.ExecuteNonQuery();
                    cmd.Parameters.Clear();
                }
                conn.Close();
            }
        }
    }
    catch (Exception ex)
    {
        return ex;
    }
    return null;
}

This test fails however if I change the method to assert an equality on the return value and an InvalidOperationException and I am given the following message: 但是,如果我更改方法以在返回值和InvalidOperationException上声明相等,则此测试失败,并且得到以下消息:

Message: Assert.AreEqual failed. 消息:Assert.AreEqual失败。 Expected:System.InvalidOperationException: Operation is not valid due to the current state of the object. Expected:System.InvalidOperationException:由于对象的当前状态,操作无效。 Actual:System.InvalidOperationException: ExecuteNonQuery: CommandText property has not been initialized Actual:System.InvalidOperationException:ExecuteNonQuery:CommandText属性尚未初始化

I've also duplicated the code to a separate project file to ensure the called method returns an InvalidOperationException, and it does. 我还将代码复制到一个单独的项目文件中,以确保所调用的方法返回InvalidOperationException,并且确实如此。 What am I missing? 我想念什么?

Your method is returning an exception, not throwing an exception. 你的方法返回一个例外,而不是抛出异常。 The ExpectedExceptionAttribute expects your method to throw an unhandled exception. ExpectedExceptionAttribute期望您的方法抛出未处理的异常。 This line: 这行:

return ex;

returns the exception. 返回异常。 Instead, just replace it with 相反,只需将其替换为

throw;

or remove the try/catch entirely, since catching and doing nothing but rethrowing is the same as not catching it in the first place. 或完全删除try / catch,因为除了重新抛出外,仅捕获和执行其他操作与一开始就不捕获相同。

I'd also question if it makes sense for the function to return an Exception . 我还要问函数返回Exception是否有意义。

public static Exception ExecuteSQL(List<int> walletList, string command)

Is that really what you want, or should it return the result of executing the query? 那真的是您想要的,还是应该返回执行查询的结果? The function should return what you expect to receive, perhaps in this case a value from the query or a response indicating that it was executed. 该函数应该返回您希望接收的内容,在这种情况下,可能是查询的值或表明已执行的响应。 You don't have to return an exception. 您不必返回异常。 If one is thrown, it automatically gets bubbled up to the calling method. 如果抛出一个,它将自动冒泡至调用方法。 That method can handle it, or if it doesn't, it bubbles up to the next method, and so on. 该方法可以处理它,或者如果不能处理,则冒泡到下一个方法,依此类推。


That also explains the error you get if you change the test to assert equality. 这也解释了如果您将测试更改为断言相等时会遇到的错误。 Whatever the return value you expect is, you're checking to see if it's equal to an Exception . 无论您期望的返回值是什么,都在检查它是否等于Exception

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM