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

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

    (Sry it's 6 months late, hope this won't be considered necroposting I landed here looking for how to throw a SqlCeException from a mock).

    If you just need to test the code that handles the exception an ultra simple workaround would be:

    public void MyDataMethod(){
        try
        {
            myDataContext.SubmitChanges();
        }
        catch(Exception ex)
        {
            if(ex is SqlCeException || ex is TestThrowableSqlCeException)
            {
                // handle ex
            }
            else
            {
                throw;
            }
        }
    }
    
    
    
    public class TestThrowableSqlCeException{
       public TestThrowableSqlCeException(string message){}
       // mimic whatever properties you needed from the SqlException:
    }
    
    var repo = new Rhino.Mocks.MockReposity();
    mockDataContext = repo.StrictMock();
    Expect.Call(mockDataContext.SubmitChanges).Throw(new TestThrowableSqlCeException());
    

提交回复
热议问题