使用XUnit声明异常

编程入门 行业动态 更新时间:2024-10-19 02:14:52
本文介绍了使用XUnit声明异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我是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("")); }

如果一意孤行,可以将操作提取到它自己的变量中。

If bent on following AAA you can extract the action into it's 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

如果进行异步测试,请声明。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声明异常

本文发布于:2023-11-14 19:47:36,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1588358.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:异常   声明   XUnit

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!