简体   繁体   English

使用Moq,有没有办法声明性地配置模拟对象以引发异常?

[英]Using Moq, is there a way to declaratively configure a mock object to throw an exception?

I've used Moq's linq to mocks feature before but only for setting properties or return values from simple functions. 我以前曾使用Moq的linq来模拟功能,但仅用于设置属性或从简单函数返回值。 I'm curious whether there is a way to configure a mock object to throw an exception using Mock.Of<> ? 我很好奇是否有一种方法可以配置模拟对象以使用Mock.Of<>引发异常?

It accepts an Expression<Func<T, bool>> as a predicate. 它接受Expression<Func<T, bool>>作为谓词。 If it is capable of using a linq expression to configure a mocked method to throw an exception, I'm drawing a blank on the correct syntax to do it. 如果它能够使用linq表达式配置一个模拟方法来引发异常,那么我将在正确的语法上画一个空白来做到这一点。

Is this even possible? 这有可能吗?

From the Quickstart : 快速入门

LINQ to Mocks is great for quickly stubbing out dependencies that typically don't need further verification. LINQ to Mocks非常适合快速建立通常不需要进一步验证的依赖项。 If you do need to verify later some invocation on those mocks, you can easily retrieve them with Mock.Get(instance) . 如果以后确实需要验证这些Mock.Get(instance)某些调用,则可以使用Mock.Get(instance)轻松检索它们。

Though it does not mention exceptions explicitly the same applies to them as well: 尽管没有明确提及异常,但它们同样适用于它们:

var mockService = Mock.Of<ISomeService>(/*your usual declarative setup*/);

// adding exceptions by reverting to classic setup:
Mock.Get(mockService).Setup(s => s.MyMethod()).Throws(myException); // or Returns/Verify/etc.

So the best you can do is to mix the two ways. 因此,您最好的办法是将两种方式混合使用。 Simple setup can be done by the Mock.Of<> and verification/exceptions can be added by retrieving the internally created mock by Mock.Get() . 可以通过Mock.Of<>进行简单设置,并可以通过检索Mock.Get()内部创建的模拟来添加验证/例外。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM