【发布时间】:2017-10-14 20:43:13
【问题描述】:
我一直在使用 NUnit 进行测试,我非常喜欢测试用例。在 NUnit 中,您可以使用 TestCaseData 类中的 SetName 函数轻松设置测试用例中的每个测试名称。
xUnit 有类似的功能吗?
目前我只能在测试资源管理器中看到一个测试,即使我在测试用例中有 6 个测试。
xUnit 测试
public class LogHandler : TestBase
{
private ILogger _logger;
public LogHandler()
{
//Arrange
LogAppSettings logAppSettings = GetAppSettings<LogAppSettings>("Log");
IOptions<LogAppSettings> options = Options.Create(logAppSettings);
LogService logService = new LogService(new Mock<IIdentityService>().Object, options);
LogProvider logProvider = new LogProvider(logService);
_logger = logProvider.CreateLogger(null);
}
public static IEnumerable<object[]> TestCases => new[]
{
new object[] { LogLevel.Critical,
new EventId(),
new Exception(),
1 },
new object[] { LogLevel.Error,
new EventId(),
new Exception(),
1 },
new object[] { LogLevel.Warning,
new EventId(),
new Exception(),
0 },
new object[] { LogLevel.Information,
new EventId(),
new Exception(),
0 },
new object[] { LogLevel.Debug,
new EventId(),
new Exception(),
0 },
new object[] { LogLevel.Trace,
new EventId(),
new Exception(),
0 },
new object[] { LogLevel.None,
new EventId(),
new Exception(),
0 }
};
[Theory, MemberData(nameof(TestCases))]
public void Test(LogLevel logLevel, EventId eventId, Exception exception, int count)
{
//Act
_logger.Log<object>(logLevel, eventId, null, exception, null);
//Assert
int exceptionCount = Database.Exception.Count();
Assert.Equal(exceptionCount, count);
}
}
xUnit 测试窗口
这里应该是 6 个测试而不是 1 个! (忽略 GetOrganisationStatuses)。
NUnit 测试用例
public static IEnumerable TestDatabaseCases
{
get
{
yield return new TestCaseData(LogLevel.Critical,
new EventId(1),
new Exception("Exception"),
0,
1).SetName("InsertException_Should_Insert_When_LogLevel_Critical");
yield return new TestCaseData(LogLevel.Error,
new EventId(1),
new Exception("Exception"),
0,
1).SetName("InsertException_Should_Insert_When_LogLevel_Error");
yield return new TestCaseData(LogLevel.Warning,
new EventId(1),
new Exception("Exception"),
0,
0).SetName("InsertException_Should_Not_Insert_When_LogLevel_Warning");
yield return new TestCaseData(LogLevel.Information,
new EventId(1),
new Exception("Exception"),
0,
0).SetName("InsertException_Should_Not_Insert_When_LogLevel_Information");
yield return new TestCaseData(LogLevel.Debug,
new EventId(1),
new Exception("Exception"),
0,
0).SetName("InsertException_Should_Not_Insert_When_LogLevel_Debug");
}
}
NUnit 测试窗口
这就是我想要的 xUnit!
如何在 xUnit 中为测试用例中的每个测试设置名称?
【问题讨论】:
-
我之前也遇到过同样的问题。您的类将需要从 IXunitSerializable 继承。实现起来比较麻烦。。不知道有没有更好的方法。
-
有一个现成的实现,它绕过了更改被测代码和测试代码的需要。只需包含新的自定义 xUnit TheoryAttribute、XunitDiscoverer 类和两个测试类 - 有关详细信息和 MIT 许可的工作代码,请参见第二个答案。
标签: c# asp.net .net asp.net-core xunit