Reputation: 53
Here is my unit test method
[Fact]
public void DealerSmsStatusTestTest_MustReturnInternalServerErrorIfMockMethodFails()
{
//Arrange
Mock<DBClass.IDealer> mock = new Mock<DBClass.IDealer>();
var exception = FormatterServices.GetUninitializedObject(typeof(System.Data.SqlClient.SqlException));
mock.Setup(x => x.GetDealerStatus(new System.Net.Http.HttpRequestMessage()))
.Throws((System.Data.SqlClient.SqlException)exception);
DealerSettingController controller = new DealerSettingController(mock.Object);
//Act
var result = controller.DealerSmsStatus();
//Assert
/*I will do assertion here*/
}
And here is my controller method
public IHttpActionResult DealerSmsStatus()
{
try
{
var result = _dealer.GetDealerStatus(Request);
return Json(new Models.Response(
Models.ResponseMessages.Success,
result)
);
}
catch (System.Data.SqlClient.SqlException)
{
return InternalServerError();
}
catch (System.Exception ex)
{
Logger.Error(ex, ex.Message, ex.StackTrace);
return InternalServerError();
}
}
When i debug the test, GetDealerStatus()
method should return SqlException
instead it returns null. In controller method var result
always getting null. Any suggestions appreciated why it is not working.I want to throw SqlException
through GetDealerStatus()
.
Here is debug mode result
value image
Upvotes: 1
Views: 1109
Reputation: 3203
It's probably the matcher x.GetDealerStatus(new System.Net.Http.HttpRequestMessage())
new System.Net.Http.HttpRequestMessage()
creates a new instance of a HttpRequestMessage
which will not be equal to the Request
you're passing into GetDealerStatus
in your SUT.
Normally you'd use something like:
x.GetDealerStatus(It.IsAny<System.Net.Http.HttpRequestMessage>())
or
It.Is<System.Net.Http.HttpRequestMessage>(x => whatever specific equality conditions you want to match on)
if you want to narrow the match condition from just 'any'
Upvotes: 0
Reputation: 706
You should use It.IsAny<System.Net.Http.HttpRequestMessage>()
instead of new System.Net.Http.HttpRequestMessage()
at Setup
. Because you configured your method for concrete instance of System.Net.Http.HttpRequestMessage
, at test it's not the same.
Upvotes: 2