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

前端 未结 14 1679
孤街浪徒
孤街浪徒 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:25

    This should work:

    SqlConnection bogusConn = 
        new SqlConnection("Data Source=myServerAddress;Initial
        Catalog=myDataBase;User Id=myUsername;Password=myPassword;");
    bogusConn.Open();
    

    That takes a bit before it throws the exception, so I think this would work even faster:

    SqlCommand bogusCommand = new SqlCommand();
    bogusCommand.ExecuteScalar();
    

    Code brought to you by Hacks-R-Us.

    Update: nope, the second approach throws an ArgumentException, not a SqlException.

    Update 2: this works much faster (the SqlException is thrown in less than a second):

    SqlConnection bogusConn = new SqlConnection("Data Source=localhost;Initial
        Catalog=myDataBase;User Id=myUsername;Password=myPassword;Connection
        Timeout=1");
    bogusConn.Open();
    
    0 讨论(0)
  • 2020-12-05 02:29

    I have a solution to this. I'm not sure whether it's genius or madness.

    The following code will create a new SqlException:

    public SqlException MakeSqlException() {
        SqlException exception = null;
        try {
            SqlConnection conn = new SqlConnection(@"Data Source=.;Database=GUARANTEED_TO_FAIL;Connection Timeout=1");
            conn.Open();
        } catch(SqlException ex) {
            exception = ex;
        }
        return(exception);
    }
    

    which you can then use like so (this example is using Moq)

    mockSqlDataStore
        .Setup(x => x.ChangePassword(userId, It.IsAny<string>()))
        .Throws(MakeSqlException());
    

    so that you can test your SqlException error handling in your repositories, handlers and controllers.

    Now I need to go and lie down.

    0 讨论(0)
提交回复
热议问题