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

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

    Edit Ouch: I didn't realise SqlException is sealed. I've been mocking DbException, which is an abstract class.

    You can't create a new SqlException, but you can mock a DbException, which SqlException derives from. Try this:

    var ex = new Mock();
    ex.ExpectGet(e => e.Message, "Exception message");
    
    var conn = new Mock();
    conn.Expect(c => c.Open()).Throws(ex.Object);
    

    So your exception is thrown when the method tries to open the connection.

    If you expect to read anything other than the Message property on the mocked exception then don't forget to Expect (or Setup, depending on your version of Moq) the "get" on those properties.

提交回复
热议问题