使用UnitTests c#进行测试时,请进行NLog日志记录

问题描述 投票:0回答:1

正如标题所说,我希望在使用XUnit运行单元测试时不会忽略我的Logger。我还想要记录。如果可以,可以怎样做?

这是我的配置

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

  <targets>
    <target name="log"
       xsi:type="File"
       fileName="${basedir}/logs/log.${longdate:cached=true}.log"
       layout="${message}"
       archiveFileName="${basedir}/logs/archives/log.${shortdate}.{#}.log"
       archiveAboveSize="5242880"
       archiveEvery="Day"
       archiveNumbering = "Rolling"
       maxArchiveFiles="20"
     />
    <target name="logconsole" xsi:type="Console" />
  </targets>

  <rules>
    <logger name="*" minlevel="Info" writeTo="logconsole" />
    <logger name="*" minlevel="trace" writeTo="log" />
  </rules>
</nlog>

我只有一个后端而且没有前端,所以当我运行测试时我想看到一切都记录:)

c# unit-testing nlog xunit
1个回答
1
投票

您可以在单元测试中使用NLog。不幸的是,NLog很难找到nlog.config的路径,因为单元测试框架会在文件夹之间移动二进制文件 - 而不是nlog.config。

它在不同的环境/框架中也是不同的(NUnit,xUnit,MSTest,.NET full,.NET Core)

你可以这样做:

  • 在C#中编写配置。见Docs
  • 或者告诉NLog配置的路径: LogManager.Configuration = new XmlLoggingConfiguration("pathToNLogConfig/nlog.config");

还建议用于登录单元测试,写入内存目标而不是文件/数据库等。您还可以在代码中检索记录的事件。见memory target docs

© www.soinside.com 2019 - 2024. All rights reserved.