我是 XUnit 和 Moq 的新手.我有一个将字符串作为参数的方法.如何使用 XUnit 处理异常.
I am a newbie to XUnit and Moq. I have a method which takes string as an argument.How to handle an exception using XUnit.
[Fact] public void ProfileRepository_GetSettingsForUserIDWithInvalidArguments_ThrowsArgumentException() { //arrange ProfileRepository profiles = new ProfileRepository(); //act var result = profiles.GetSettingsForUserID(""); //assert //The below statement is not working as expected. Assert.Throws<ArgumentException>(() => profiles.GetSettingsForUserID("")); }被测方法
public IEnumerable<Setting> GetSettingsForUserID(string userid) { if (string.IsNullOrWhiteSpace(userid)) throw new ArgumentException("User Id Cannot be null"); var s = profiles.Where(e => e.UserID == userid).SelectMany(e => e.Settings); return s; } 推荐答案Assert.Throws 表达式将捕获异常并断言类型.但是,您在断言表达式之外调用了被测方法,从而导致测试用例失败.
The Assert.Throws expression will catch the exception and assert the type. You are however calling the method under test outside of the assert expression and thus failing the test case.
[Fact] public void ProfileRepository_GetSettingsForUserIDWithInvalidArguments_ThrowsArgumentException() { //arrange ProfileRepository profiles = new ProfileRepository(); // act & assert Assert.Throws<ArgumentException>(() => profiles.GetSettingsForUserID("")); }如果一心追随 AAA,您可以将动作提取到它自己的变量中.
If bent on following AAA you can extract the action into its own variable.
[Fact] public void ProfileRepository_GetSettingsForUserIDWithInvalidArguments_ThrowsArgumentException() { //arrange ProfileRepository profiles = new ProfileRepository(); //act Action act = () => profiles.GetSettingsForUserID(""); //assert ArgumentException exception = Assert.Throws<ArgumentException>(act); //The thrown exception can be used for even more detailed assertions. Assert.Equal("expected error message here", exception.Message); }注意如何将异常也用于更详细的断言
Note how the exception can also be used for more detailed assertions
如果是异步测试,Assert.ThrowsAsync与前面给出的示例类似,除了应等待断言,
If testing asynchronously, Assert.ThrowsAsync follows similarly to the previously given example, except that the assertion should be awaited,
public async Task Some_Async_Test() { //... //Act Func<Task> act = () => subject.SomeMethodAsync(); //Assert var exception = await Assert.ThrowsAsync<InvalidOperationException>(act); //... }更多推荐
使用 XUnit 断言异常
发布评论