rex*_*ghk 6 c# xunit.net async-await
我有一些测试代码断言重复Users无法通过我创建UserRepository.
User.cs:
public class User
{
public int Id { get; set; }
public string AccountAlias { get; set; }
public string DisplayName { get; set; }
public string Email { get; set; }
public bool IsActive { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
UserRepository.cs:
public class UserRepository
{
public virtual async Task<User> CreateAsync(User entity)
{
if (entity == null)
{
throw new ArgumentNullException("entity");
}
if (await GetDuplicateAsync(entity) != null)
{
throw new InvalidOperationException("This user already exists");
}
return Create(entity);
}
public async Task<User> GetDuplicateAsync(User user)
{
if (user == null)
{
throw new ArgumentNullException("user");
}
return await (from u in Users
where u.AccountAlias == user.AccountAlias &&
u.Id != user.Id &&
u.IsActive
select u).FirstOrDefaultAsync();
}
}
Run Code Online (Sandbox Code Playgroud)
UserRepositoryTests.cs:
public sealed class UserRepositoryTests : IDisposable
{
public UserRepositoryTests()
{
UserRepository = new UserRepository(new FooEntities()); // DbContext
// from EF
}
private UserRepository UserRepository { get; set; }
[Fact]
public void DuplicateUserCannotBeCreated()
{
var testUser = new User // This test user already exists in database
{
Id = 0,
AccountAlias = "domain\\foo",
DisplayName = "Foo",
Email = "foo@bar.com",
IsActive = true
};
Assert.Throws<InvalidOperationException>(async () =>
await UserRepository.CreateAsync(testUser));
}
public void Dispose()
{
if (UserRepository != null)
{
UserRepository.Dispose();
}
}
}
Run Code Online (Sandbox Code Playgroud)
当我运行这个单元测试,Xunit.Sdk.ThrowsException被抛出(即我InvalidOperationException是不是抛出):
Assert.Throws()预期失败:System.InvalidOperationException实际:(没有抛出异常)
从调试器GetDuplicateAsync()进行了评估,但是当执行LINQ查询时,结果从未返回,因此没有抛出异常.有人可以帮忙吗?
dca*_*tro 18
xUnit Assert.Throws(至少在版本1.9.2上)不是异步感知的.这已在版本2中修复,现在有一个Assert.ThrowsAsync方法.
因此,您可以升级到xUnit 2或创建自己的方法以使其正常工作:
public async static Task<T> ThrowsAsync<T>(Func<Task> testCode) where T : Exception
{
try
{
await testCode();
Assert.Throws<T>(() => { }); // Use xUnit's default behavior.
}
catch (T exception)
{
return exception;
}
return null;
}
await ThrowsAsync<InvalidOperationException>(async () => await UserRepository.CreateAsync(testUser));
Run Code Online (Sandbox Code Playgroud)
来自Haacked的要点.