Moq – Mocking the Request context and verifying SQLException is raised.

Mocking the Request on an API Controller

Had an API controller under unit test which made use of the HttpMessageRequest which I needed to mock.How do I get a handle on this?

Again pretty simple really (my initial train of thought was back to front on this one)

var request = new HttpMessageRequest(HttpMethod.Get, "http://....."
controllerUnderTest.request = request;

Verifying that a SQLException is raised.



I was unable to mock

.Throws<<"SQLException">>

as SQLException has a parameterless constructor as in….

‘System.Data.SqlClient.SqlException’ must be a non-abstract type with a public parameterless constructor in order to use it as parameter ‘TException’ in the generic type or method ‘Moq.Language.IThrows.Throws()’

So what to do?

var exception = FormatterServices.GetUninitializedObject(typeof(SqlException)) as SqlException;
mockInvalidDBContext.Setup(d => d.GetConnection()).Throws(exception);

Credit to http://stackoverflow.com/questions/11976996/moq-and-throwing-a-sqlexception

Leave a Reply