使用 Moq 模拟依赖属性
如果我有一个类,它具有通过属性注入解决的依赖项,是否可以使用 Moq 来模拟该属性的行为?
例如
public class SomeClass
{
//empty constructor
public SomeClass() {}
//dependency
public IUsefuleService Service {get;set;}
public bool IsThisPossible(Object someObject)
{
//do some stuff
//I want to mock Service and the result of GetSomethingGood
var result = Service.GetSomethingGood(someObject);
}
}
,SomeClass 正在测试中,我试图弄清楚是否可以使用 Moq 模拟 IUsefulService 的行为,因此当我测试 IsThisPossible 并且使用该服务的行被命中时,将使用模拟...
If I have a class that has a dependency that is resolved via property injection, is it possible to Mock the behavior of that property using Moq?
e.g.
public class SomeClass
{
//empty constructor
public SomeClass() {}
//dependency
public IUsefuleService Service {get;set;}
public bool IsThisPossible(Object someObject)
{
//do some stuff
//I want to mock Service and the result of GetSomethingGood
var result = Service.GetSomethingGood(someObject);
}
}
So, SomeClass is under test and I am trying to figure out if I can mock the behavior of IUsefulService with Moq so when I test IsThisPossible and the line using the service is hit, the mock is used...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我可能误解并过度简化了问题,但我认为下面的代码应该有效。由于您将
Service
属性作为公共属性,因此您可以模拟IUsefulService
,新建SomeClass
,然后设置Service将
属性添加到您的模拟中。SomeClass
上的希望有帮助。如果我遗漏了什么,请告诉我,我会看看我能做什么。
I may be misunderstanding and oversimplifying the question, but I think code below should work. Since you have the
Service
property as a public property, you can just mockIUsefulService
, new upSomeClass
, and then set theService
property onSomeClass
to your mock.Hope that helps. If I'm missing something let me know and I'll see what I can do.