|
|
namespace OptionsPattern.Sutdy.Advanced
|
|
|
{
|
|
|
public class UseXunitTest:IDisposable
|
|
|
{
|
|
|
private readonly ITestOutputHelper? _output;
|
|
|
private readonly IConfiguration _defaultConfig;
|
|
|
public UseXunitTest(ITestOutputHelperAccessor outputHelperAccessor,IConfiguration configuration)
|
|
|
{
|
|
|
if (outputHelperAccessor == null)
|
|
|
{
|
|
|
throw new ArgumentNullException(nameof(outputHelperAccessor));
|
|
|
}
|
|
|
|
|
|
if (outputHelperAccessor == null)
|
|
|
{
|
|
|
throw new ArgumentNullException($"参数 {nameof(outputHelperAccessor)} 为 null, 请在 Startup.cs 中注册 IConfiguration");
|
|
|
}
|
|
|
|
|
|
_output = outputHelperAccessor.Output;
|
|
|
_defaultConfig = configuration;
|
|
|
}
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
/// xUnit 可用性测试
|
|
|
/// </summary>
|
|
|
[Fact]
|
|
|
public void UsabilityTest()
|
|
|
{
|
|
|
Assert.True(true, "6.2 配置选项进阶,使用xUnit测试框架!");
|
|
|
_output?.WriteLine("6.2 配置选项 进阶!");
|
|
|
}
|
|
|
|
|
|
/// <summary>
|
|
|
/// 从IoC中获取默认配置
|
|
|
/// 1、引入 Xunit.DependencyInjection 库
|
|
|
/// 2、Startup.cs 中设置默认配置
|
|
|
/// </summary>
|
|
|
[Fact]
|
|
|
public void GetIConfiguration_FromDI_ByStartup_Test()
|
|
|
{
|
|
|
var appOption = _defaultConfig.Get<AppOption>();
|
|
|
|
|
|
Assert.NotNull(_defaultConfig);
|
|
|
Assert.NotNull(appOption);
|
|
|
Assert.Contains(nameof(AppOption.AppName), appOption.AppName);
|
|
|
}
|
|
|
|
|
|
/// <summary>
|
|
|
/// 断言不发生异常
|
|
|
/// 使用:xUnit 变通方法
|
|
|
/// </summary>
|
|
|
[Fact]
|
|
|
public void DoesNotThrow_Test()
|
|
|
{
|
|
|
//待执行代码段
|
|
|
Action codeSnippet = () =>
|
|
|
{
|
|
|
//业务代码
|
|
|
|
|
|
//模拟异常
|
|
|
//throw new Exception("我是特意抛出的异常!");
|
|
|
};
|
|
|
|
|
|
var exception = Record.Exception(codeSnippet);
|
|
|
Assert.Null(exception);
|
|
|
|
|
|
_output?.WriteLine("使用 xUnit 变通方法,断言不发生异常!");
|
|
|
}
|
|
|
|
|
|
/// <summary>
|
|
|
/// 断言不发生异常
|
|
|
/// 使用:FluentAssertions 库方式,断言不发生异常
|
|
|
/// </summary>
|
|
|
[Fact]
|
|
|
public void DoesNotThrow_UseFluentAssertions_Test()
|
|
|
{
|
|
|
//待执行代码段
|
|
|
Action codeSnippet= () =>
|
|
|
{
|
|
|
//业务代码
|
|
|
|
|
|
//模拟异常
|
|
|
//throw new Exception("我是特意抛出的异常!");
|
|
|
};
|
|
|
|
|
|
//断言:不发生异常
|
|
|
codeSnippet.Should().NotThrow();
|
|
|
|
|
|
_output?.WriteLine("使用 FluentAssertions 库方式,断言不发生异常!");
|
|
|
}
|
|
|
|
|
|
/// <summary>
|
|
|
/// 清理
|
|
|
/// </summary>
|
|
|
public void Dispose()
|
|
|
{
|
|
|
}
|
|
|
}
|
|
|
} |