我在玩Visual Studio 11 Beta。如何测试异步方法中的异常
鉴于此代码:
namespace KC.DataAccess.Global
{
/// <summary>Global methods for SQL access</summary>
public static class SQL
{
public async static void ExecuteNonQuery(string ConnStr, string Query)
{
if (string.IsNullOrEmpty(ConnStr)) throw new ArgumentNullException("ConnStr");
if (string.IsNullOrEmpty(Query)) throw new ArgumentNullException("Query");
SqlConnection conn = new SqlConnection(ConnStr);
SqlCommand cmd = PrepSqlConnection(ref conn, Query);
Exception exc = null;
for (int i = 0; i < 3; i++)
try { await Task.Run(() => cmd.ExecuteNonQuery()); break; }
catch (Exception ex) { Thread.Sleep(50); exc = ex; }
if (exc != null) throw new ApplicationException("Command failed after maximum attempts", exc);
conn.Close();
conn.Dispose();
}
}
}
因为它是一个异步方法,异常似乎并不冒泡调用方法。我有测试用例因此这会失败:
using Target = KC.DataAccess.Global.SQL;
[TestMethod]
[TestCategory("Unit")]
[ExpectedException(typeof(ArgumentNullException))]
public void ExecuteNonQueryFail1()
{
Target.ExecuteNonQuery(null, "select 1");
}
的ExecuteNonQuery的验证部分显然在这种情况下抛出一个异常,我看到它扔在我调试。
我已将测试方法更改为异步并且语法为等待Task.Run(()=> Target.ExecuteNonQuery()),无济于事。
问题:
- 是的ExecuteNonQuery抛出异常呢?
- 为什么ExecuteNonQueryFail1看不到异常?
- 如何更改测试方法或方法本身,以正确处理异常并通过测试用例,而不会放弃方法的异步性质?
注意当我改变目标方法返回一个任务发生此相同的行为,当我能够在测试的配置文件ThrowUnobservedTaskExceptions。 – tsilb 2012-03-03 06:11:59
您应该使用'TaskEx.Delay'而不是'Thread.Sleep'。 – 2012-03-04 01:40:20