使用XUnit断言exception

我是XUnit和Moq的新手。 我有一个方法,它将字符串作为参数。如何使用XUnit处理exception。

[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(() => profiles.GetSettingsForUserID("")); } 

测试方法

 public IEnumerable 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表达式将捕获exception并断言类型。 但是,您正在调用断言表达式之外的测试方法,从而使测试用例失败。

 [Fact] public void ProfileRepository_GetSettingsForUserIDWithInvalidArguments_ThrowsArgumentException() { //arrange ProfileRepository profiles = new ProfileRepository(); // act & assert Assert.Throws(() => profiles.GetSettingsForUserID("")); } 

如果遵循AAA,你可以将动作提取到它自己的变量中

 [Fact] public void ProfileRepository_GetSettingsForUserIDWithInvalidArguments_ThrowsArgumentException() { //arrange ProfileRepository profiles = new ProfileRepository(); //act Action act = () => profiles.GetSettingsForUserID(""); //assert Assert.Throws(act); } 

如果您确实想要对AAA非常严格,那么您可以使用xUnit中的Record.Exception来捕获Act阶段中的Exception。

然后,您可以根据Assert阶段中捕获的exception进行断言。

在xUnits测试中可以看到这方面的一个例子。

 [Fact] public void Exception() { Action testCode = () => { throw new InvalidOperationException(); }; var ex = Record.Exception(testCode); Assert.NotNull(ex); Assert.IsType(ex); } 

这取决于您想要遵循的路径,xUnit提供的路径完全支持这两条路径。