[英]Mock function not throwing exception in c# unit test
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 .当我调试测试时,
GetDealerStatus()
方法应该返回SqlException
而不是它返回null 。 In controller method var result
always getting null .在控制器方法
var result
总是得到null 。 Any suggestions appreciated why it is not working.I want to throw SqlException
through GetDealerStatus()
.任何建议都表示赞赏为什么它不起作用。我想通过
GetDealerStatus()
抛出SqlException
。 Here is debug mode result
value image这是调试模式
result
值图像
You should use It.IsAny<System.Net.Http.HttpRequestMessage>()
instead of new System.Net.Http.HttpRequestMessage()
at Setup
.您应该在
Setup
使用It.IsAny<System.Net.Http.HttpRequestMessage>()
而不是new System.Net.Http.HttpRequestMessage()
。 Because you configured your method for concrete instance of System.Net.Http.HttpRequestMessage
, at test it's not the same.因为您为
System.Net.Http.HttpRequestMessage
具体实例配置了您的方法,所以在测试中它不一样。
It's probably the matcher x.GetDealerStatus(new System.Net.Http.HttpRequestMessage())
这可能是匹配器
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. new System.Net.Http.HttpRequestMessage()
创建一个HttpRequestMessage
的新实例,它不等于您在 SUT 中传递给GetDealerStatus
的Request
。
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'如果您想将匹配条件从“任何”缩小
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.