Web API Nunit测试不注入依赖项

时间:2016-02-12 18:41:51

标签: asp.net-web-api dependency-injection nunit simple-injector

当我尝试对我的web api项目进行单元测试时,我收到了错误

  

{[消息,发生了错误。]}   ExceptionMessage,尝试创建“ExampleController”类型的控制器时发生错误。确保控制器具有无参数的公共构造函数。   {[ExceptionType,System.InvalidOperationException]}   {[StackTrace,在System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage请求,HttpControllerDescriptor controllerDescriptor,类型controllerType))      在System.Web.Http.Controllers.HttpControllerDescriptor.CreateController(HttpRequestMessage请求)      在System.Web.Http.Dispatcher.HttpControllerDispatcher.d__1.MoveNext()]}   {[InnerException,System.Web.Http.HttpError]}

单元测试:

[TestFixtureSetUp]
public void TestsSetup()
{
    _server = HttpRequestHelper.SetupHttpServerDefault();
}

[Test]
public void CanGetAllAddresses()
{
    var client = new HttpClient(_server);

    var request = HttpRequestHelper.CreateRequest("memory/address", HttpMethod.Get, ConfigurationManager.AppSettings["KeyUser"], string.Empty, ConfigurationManager.AppSettings["SecretUser"]);
    using (HttpResponseMessage response = client.SendAsync(request).Result)
    {
        Assert.NotNull(response.Content);
    }
}

我在一个涉及这个逻辑的nunit TestFixtureSetUp函数中注册我的控制器:

public static HttpServer SetupHttpServerDefault()
{
    var config = new HttpConfiguration();
    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "memory/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );

    var container = new Container();
    container.Register<IAddressService, AddressService>();
    var services = GlobalConfiguration.Configuration.Services;
    var controllerTypes = services.GetHttpControllerTypeResolver().
            GetControllerTypes(services.GetAssembliesResolver());
    foreach (var controllerType in controllerTypes)
    {
      var registration = Lifestyle.Transient.
          CreateRegistration(controllerType, container);

      container.AddRegistration(controllerType, registration);

      registration.SuppressDiagnosticWarning
                   (DiagnosticType.DisposableTransientComponent, "");
    }
    container.Verify();
    GlobalConfiguration.Configuration.DependencyResolver = new 
                    SimpleInjectorWebApiDependencyResolver(container);
    return new HttpServer(config);
}

我的地址控制器就像这样开始:

public class AddressController : BaseController
{
    private readonly IAddressService _addressService;

    public AddressController(IAddressService addressService)
    {
        _addressService = addressService;
    }
}

当删除控制器参数时,我可以调试到控制器,告诉我我没有正确地将依赖项注入控制器。我查看了这篇看起来很相似的帖子here,但我不熟悉如何明确声明我的控制器。我尝试使用类似的方法来处理我的服务但是我没有工作。

1 个答案:

答案 0 :(得分:2)

我的特定问题的解决方案实际上是在我在测试中创建的内存HttpServerGlobalConfiguration上注册依赖项解析器。在问题的上方,您将看到config变量的创建,然后这是修复我的问题的代码:

config.DependencyResolver = new SimpleInjectorWebApiDependencyResolver(container); 
GlobalConfiguration.Configuration.DependencyResolver = 
                    new SimpleInjectorWebApiDependencyResolver(container);

没有config.DependencyResolver,我无法通过以下方式连接到我的项目控制器:

using (HttpResponseMessage response = client.SendAsync(request).Result)

没有GlobalConfiguration.Configuration.DependencyResolver,我无法在我的测试项目中本地联系服务。希望这有助于其他人!