如果我有一个具有通过属性注入解析的依赖项的类,是否可以使用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);
}
}
所以,SomeClass正在测试中,我试图找出是否可以使用Moq模拟IUsefulService的行为,所以当我测试IsThisPossible并且使用该服务的行被命中时,使用了mock ...
答案 0 :(得分:7)
我可能会误解并过度简化这个问题,但我认为下面的代码应该有效。由于您将Service
属性作为公共属性,因此您可以模拟IUsefulService
,新建SomeClass
,然后将Service
属性设置为SomeClass
你的模拟。
using System;
using NUnit.Framework;
using Moq;
namespace MyStuff
{
[TestFixture]
public class SomeClassTester
{
[Test]
public void TestIsThisPossible()
{
var mockUsefulService = new Mock<IUsefulService>();
mockUsefulService.Setup(a => a.GetSomethingGood(It.IsAny<object>()))
.Returns((object input) => string.Format("Mocked something good: {0}", input));
var someClass = new SomeClass {Service = mockUsefulService.Object};
Assert.AreEqual("Mocked something good: GOOD!", someClass.IsThisPossible("GOOD!"));
}
}
public interface IUsefulService
{
string GetSomethingGood(object theObject);
}
public class SomeClass
{
//empty constructor
public SomeClass() { }
//dependency
public IUsefulService Service { get; set; }
public string IsThisPossible(Object someObject)
{
//do some stuff
//I want to mock Service and the result of GetSomethingGood
var result = Service.GetSomethingGood(someObject);
return result;
}
}
}
希望有所帮助。如果我遗失某些东西让我知道,我会看到我能做些什么。