我正在为基于OWIN的Web API进行一些集成测试。我使用结构图作为DI容器。在其中一个案例中,我需要模拟一个API调用(不能将其作为测试的一部分包含在内)。
我如何使用结构图进行此操作?我使用SimpleInjector完成了它,但我正在使用的代码库是使用结构图,我无法弄清楚如何做到这一点。
使用SimpleInjector解决方案:
Startup.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);
}
在我的Integration测试中,我模拟了调用其他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);
}
我在结构图文档中找到this,但它不允许我在那里注入一个模拟对象(只有类型)。
运行集成测试时如何注入模拟版本的IShopApiHelper(Mock)? (我使用Moq库进行模拟)
答案 0 :(得分:1)
假设与原始示例中的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);
}