结构图 - 在运行时将接口替换为模拟对象



我正在为我的基于 OWIN 的 Web API 做一些集成测试。我正在使用结构图作为 DI 容器。在一种情况下,我需要模拟一个 API 调用(不能将其作为测试的一部分(。

我将如何使用结构图来做到这一点?我已经使用 SimpleInjector 完成了它,但我正在处理的代码库正在使用结构图,我不知道我将如何做到这一点。

使用简单注射器的解决方案:

启动.cs

public void Configuration(IAppBuilder app)
{
var config = new HttpConfiguration();
app.UseWebApi(WebApiConfig.Register(config));
// Register IOC containers
IOCConfig.RegisterServices(config);
}

ICOCConfig:

public static Container Container { get; set; }
public static void RegisterServices(HttpConfiguration config)
{            
Container = new Container();
// Register            
config.DependencyResolver = new SimpleInjectorWebApiDependencyResolver(Container);
}

在我的集成测试中,我模拟了调用其他 API 的接口。

private TestServer testServer;
private Mock<IShopApiHelper> apiHelper;
[TestInitialize]
public void Intitialize()
{
testServer= TestServer.Create<Startup>();
apiHelper= new Mock<IShopApiHelper>();
}
[TestMethod]
public async Task Create_Test()
{
//Arrange
apiHelper.Setup(x => x.CreateClientAsync())
.Returns(Task.FromResult(true);
IOCConfig.Container.Options.AllowOverridingRegistrations = true;
IOCConfig.Container.Register<IShopApiHelper>(() => apiHelper.Object, Lifestyle.Transient);
//Act
var response = await testServer.HttpClient.PostAsJsonAsync("/api/clients", CreateObject());
//Assert
Assert.AreEqual(HttpStatusCode.Created, response.StatusCode);
}

我在结构图文档中找到了这个,但它不允许我在其中注入模拟对象(仅限类型(。

如何在运行集成测试时注入 IShopApiHelper (Mock( 的模拟版本?(我正在使用最小起订量库进行模拟(

假设与原始示例中的 API 结构相同,您可以执行与链接文档中演示的基本相同的操作。

[TestMethod]
public async Task Create_Test() {
//Arrange
apiHelper.Setup(x => x.CreateClientAsync())
.Returns(Task.FromResult(true);
// Use the Inject method that's just syntactical
// sugar for replacing the default of one type at a time    
IOCConfig.Container.Inject<IShopApiHelper>(() => apiHelper.Object);
//Act
var response = await testServer.HttpClient.PostAsJsonAsync("/api/clients", CreateObject());
//Assert
Assert.AreEqual(HttpStatusCode.Created, response.StatusCode);
}

最新更新