NUnitunit testing具有“ExpectedException”但仍然在exception时失败

我有一个unit testing失败,因为抛出了System.ArgumentException ,即使我期待它并且它是故意的行为 – 我错过了什么?

 [Test] [ExpectedException(typeof(ArgumentException), ExpectedMessage = "Seconds from midnight cannot be more than 86400 in 010100712386401000000012")] public void TestParsingCustomReferenceWithInValidSecondsFromMidnight() { // I am expecting this method to throw an ArgumentException: CustomReference.Parse("010100712386401000000012"); } 

我也试过没有设置ExpectedMessage – 没有区别。

你试过断言语法吗?

 Assert.Throws( () => CustomReference.Parse("010100712386401000000012"), "Seconds from midnight cannot be more than 86400 in 010100712386401000000012" ); 

预期的消息是否正确? 这是CustomReference.Parse(string)抛出的完全相同的消息吗? 例如,它不是 NUnit控制台中显示的内容。

我不知道为什么这不起作用的另一个原因。 您使用的是什么版本的NUnit?

如果你这样做会怎么样?

 [TestFixture] public class CustomReferenceTests { [Test] [ExpectedException(typeof(ArgumentException))] public void TestParsingCustomReferenceWithInValidSecondsFromMidnight() { // I am expecting this method to throw an ArgumentException: CustomReference.Parse("010100712386401000000012"); } [Test] [ExpectedException(typeof(ArgumentException), ExpectedMessage = "Seconds from midnight cannot be more than 86400 in 010100712386401000000012")] public void TestParsingCustomReferenceWithInValidSecondsFromMidnightWithExpectedMessage() { // I am expecting this method to throw an ArgumentException: CustomReference.Parse("010100712386401000000012"); } } public class CustomReference { public static void Parse(string s) { throw new ArgumentException("Seconds from midnight cannot be more than 86400 in 010100712386401000000012"); } }