没有代码覆盖率的 HttpParameterBinding

HttpParameterBinding without code coverage

OpenCover On Cake 脚本未检测到我的 Owin.Testing 对某些 Api 控制器操作参数应用 HttpPArameterBiding 的用法的覆盖。

我已经创建了一种新型的 ApiController,作为与我称为 FromHeaderAttribute 的 ParameterBindingAttribute 的操作。之后,我创建了我的 Owin 测试服务器和相应的 HttpClient,并执行了请求和正确的断言以验证绑定是否正常工作。测试成功通过。

这是我的单元测试 Cake Task

Task("UnitTests")
.IsDependentOn("Build")
    .IsDependentOn("RestoreNugets")
   .DoesForEach(GetFiles($"{testsPath}/**/*.csproj"), (file) => 
    {
         var openCoverSettings = new OpenCoverSettings
        {
            OldStyle = true,
            MergeOutput = true,
            Register = "user",
            LogLevel = OpenCoverLogLevel.Verbose,
             ArgumentCustomization = args => args.Append("-coverbytest:*.Tests.dll").Append("-mergebyhash")
        }
        .WithFilter("+[AppRootName.*]*");

          var projectName = file.GetFilename().ToString().Replace(".csproj",string.Empty);

           var dotNetTestSettings = new DotNetCoreTestSettings
            {            
                Configuration = "Release",
                DiagnosticOutput = true,
                Verbosity = DotNetCoreVerbosity.Normal,
                ArgumentCustomization = (args)=>
                {
                    args.Append($"--logger \"trx;LogFileName={projectName}-TestsResults.trx\"");
                    args.Append("--filter \"TestCategory=Unit|Category=Unit\"");
                    return args;
                } 
            };
            OpenCover(context => context.DotNetCoreTest(file.FullPath, dotNetTestSettings), new FilePath($"CoverageResults.xml"), openCoverSettings);

    })
    .Finally(()=>
    {
        Information($"Copying test reports to ${outputDir}/TestsResults .... ");
        CopyFiles($"{testsPath}/**/TestResults/*.trx",$"{outputDir}/TestsResults");
       ReportGenerator($"*-CoverageResults.xml", $"{outputDir}/Reports");

    });

这是我的 XUnit 测试:

[Fact]
        [Trait("Category", "Unit")]
        public async Task WhenHeadersArePresent_SettingsShouldBeSetted()
        {
            HttpConfiguration configuration = new HttpConfiguration();
            var container = new SimpleInjector.Container();

            Mock<IApiControllerValidation> mockValidationInterface = new Mock<IApiControllerValidation>();

            ManualResetEvent resetEvent = new ManualResetEvent(false);
            Settings settingsReceived = null;
            mockValidationInterface.Setup((validator) => validator.Assert(It.IsAny<object>(), It.IsAny<object>(), It.IsAny<IDictionary<string, string>>(), It.IsAny<IHttpActionResult>()))
                .Callback<object, object, IDictionary<string, string>, IHttpActionResult>((header, body, parameters, result) => 
                {
                    settingsReceived = header as Settings;
                    resetEvent.Set();
                });

            container.RegisterInstance(mockValidationInterface.Object);

            using (var server = TestServer.Create(app =>
            {

                configuration.DependencyResolver = new SimpleInjectorWebApiDependencyResolver(container);
                configuration.MapHttpAttributeRoutes();
                app.Use((owinContext, nextHandler)=> nextHandler());
                app.UseWebApi(configuration);

            }))
            {
                var client = server.HttpClient;
                client.DefaultRequestHeaders.Add("header1", new List<string>() { "headervalue1" } );
                client.DefaultRequestHeaders.Add("header2", new List<string>() { "headervalue2" });
                var result = await client.PostAsync<Payload>("optionalHeader", new Payload("value1"), new JsonMediaTypeFormatter());
                Assert.Equal(HttpStatusCode.OK,result.StatusCode);
            };

            resetEvent.WaitOne();
            Assert.NotNull(settingsReceived);
            Assert.Equal("headervalue1", settingsReceived.Header1);
            Assert.Equal("headervalue2", settingsReceived.Header2);

        }

这是我的 Api 操作,我想测试我已经实现的 FromHEader 属性。

   [HttpPost]
    [Route("optionalHeader",Name = "PostValidation")]
    public IHttpActionResult OptionalHeaders([FromHeader]Settings settings, [FromBody]Payload payload)
    {
        var result = Ok();
        validation.Assert(settings,payload, null, result);
        return result;
    }

我希望测试的代码覆盖检测到 This 类型的使用,但这不是因为报告显示我的类型的代码覆盖为 0。

我弄清楚了问题出在哪里,它与 asp.net 框架 HttpParameterBinding 组件相关的任何内容都没有关系。

而不是像这样执行代码覆盖:

 OpenCover(context => context.DotNetCoreTest(file.FullPath, dotNetTestSettings), new FilePath($"CoverageResults.xml"), openCoverSettings);

我把它改成了这样:

    OpenCover(tool => {
        tool.XUnit2($"{testsPath}/**/**/**/**/{projectName}.dll",xUnit2Settings);
        }, new FilePath("./OpenCoverCoverageResults.xml"),openCoverSettings);

此外,构建必须在调试模式下通过配置完成,这样 OpenCover 才能使用 pdb。

我仍然不喜欢的唯一一件事是 dll 的路径通过明确的级别数来明确,我也不想复制 dll,因为这会花费更多时间。