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

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

    Based on all the other answers I created the following solution:

        [Test]
        public void Methodundertest_ExceptionFromDatabase_Logs()
        {
            _mock
                .Setup(x => x.MockedMethod(It.IsAny(), It.IsAny()))
                .Callback(ThrowSqlException);
    
            _service.Process(_batchSize, string.Empty, string.Empty);
    
            _loggermock.Verify(x => x.Error(It.IsAny(), It.IsAny()));
        }
    
        private static void ThrowSqlException() 
        {
            var bogusConn =
                new SqlConnection(
                    "Data Source=localhost;Initial Catalog = myDataBase;User Id = myUsername;Password = myPassword;Connection Timeout = 1");
            bogusConn.Open();
        }
    

提交回复
热议问题