using System;
using System.Threading.Tasks;
using AspectCore.DynamicProxy;
using Xunit;
namespace Util.Datas.Tests.XUnitHelpers {
///
/// 断言操作
///
public class AssertHelper {
///
/// 抛出异常,并从异常消息中搜索特定关键字
///
/// 异常类型
/// 操作
/// 关键字
public static TException Throws( Action action, string keyword = "" ) where TException : Exception {
var exception = GetException( action );
if( !string.IsNullOrWhiteSpace( keyword ) )
Assert.Contains( keyword, exception.Message );
return exception;
}
///
/// 获取异常
///
private static TException GetException( Action action ) where TException : Exception {
try {
var exception = Assert.Throws( action );
return (TException)exception.InnerException;
}
catch {
return Assert.Throws( action );
}
}
///
/// 抛出异常,并从异常消息中搜索特定关键字
///
/// 异常类型
/// 操作
/// 关键字
public static async Task ThrowsAsync( Func action, string keyword = "" ) where TException : Exception {
var exception = await GetExceptionAsync( action );
if( !string.IsNullOrWhiteSpace( keyword ) )
Assert.Contains( keyword, exception.Message );
return exception;
}
///
/// 获取异常
///
private static async Task GetExceptionAsync( Func action ) where TException : Exception {
try {
var exception = await Assert.ThrowsAnyAsync( action );
return (TException)exception.InnerException;
}
catch {
return await Assert.ThrowsAsync( action );
}
}
}
}