Moq and throwing a SqlException

前端 未结 4 749
庸人自扰
庸人自扰 2020-12-25 11:25

I have the following code to test that when a certain name is passed to my method, it throws a SQL exception (there is reason to that one, although it sounds a little odd).<

4条回答
  •  清歌不尽
    2020-12-25 11:37

    For me to produce an SqlException with a message it was the simplest way using the Uninitialized Object method:

    const string sqlErrorMessage = "MyCustomMessage";
    var sqlException = FormatterServices.GetUninitializedObject(typeof(SqlException)) as SqlException;
    var messageField = typeof(SqlException).GetField("_message", BindingFlags.NonPublic | BindingFlags.Instance);
    messageField.SetValue(sqlException, sqlErrorMessage);
    

提交回复
热议问题