How to throw a SqlException when needed for mocking and unit testing?

前端 未结 14 1707
孤街浪徒
孤街浪徒 2020-12-05 01:28

I am trying to test some exceptions in my project and one of the Exceptions I catch is SQlException.

It seems that you can\'t go new SqlException(

14条回答
  •  南笙
    南笙 (楼主)
    2020-12-05 02:09

    Not sure if this helps, but seems to have worked for this person (pretty clever).

    try
    {
        SqlCommand cmd =
            new SqlCommand("raiserror('Manual SQL exception', 16, 1)",DBConn);
        cmd.ExecuteNonQuery();
    }
    catch (SqlException ex)
    {
        string msg = ex.Message; // msg = "Manual SQL exception"
    }
    

    Found at: http://smartypeeps.blogspot.com/2006/06/how-to-throw-sqlexception-in-c.html

提交回复
热议问题