简体   繁体   English

如何在nunit中测试包含本地化日期的异常消息

[英]How do I test an exception message containing localized dates in nunit

I've just come across an interesting problem with one of our unit tests. 我刚刚在我们的单元测试中遇到了一个有趣的问题。 It's a case where we're trying to ensure that when a particular exceptional case is encountered, that we throw and provide a useful message to the handler - the idea is that the handler can just display (or log) that message directly. 在这种情况下,我们试图确保遇到特殊情况时,我们向处理程序抛出并提供有用的消息-想法是处理程序可以直接显示(或记录)该消息。 The problem is when the message contains a date - we want that date to be expressed using the users locale and any overrides that they may have specified on their local system. 问题是消息中包含日期时-我们希望使用用户的语言环境以及他们在本地系统上可能指定的任何替代来表示该日期。

The problem arises because we have two different CI infrastructures (don't ask - one development, one release) which for various reasons, actually have two (slightly) different date settings - one passes the test below, while the other uses a (customized) date format similar to "14Jan2014". 出现问题是因为我们有两种不同的CI基础结构(不要问-一种开发,一种版本),由于各种原因,它们实际上具有两种(略有不同)日期设置-一种通过下面的测试,而另一种使用(自定义) )日期格式,类似于“ 14Jan2014”。

[Test]
[ExpectedException(typeof(InvalidOperationException), ExpectedMessage="Invalid date: 14/01/2014")]
public void ExampleTest()
{
    var date = new DateTime(2014, 01, 14);
    throw new InvalidOperationException("Invalid date: " + date.ToString());
}

I am aware of the SetCulture and Culture attributes but I don't believe these will work due to the customized aspect of the date format on the machine. 我知道SetCultureCulture属性,但是由于机器上日期格式的自定义方面,我不相信这些属性会起作用。 Is it possible to somehow ignore the customised settings and at least use the locale's defaults for the purposes of the test? 是否有可能以某种方式忽略自定义设置,并且至少将语言环境的默认值用于测试目的?

代替使用ExpectedException属性,而是重写测试以显式捕获异常并测试消息。

You can explicitly catch the exception as mentioned by @Dave Mackersie in his answer or you can use ExpectedException attribute with exception handler 您可以按照@Dave Mackersie在其答案中提到的方式明确捕获异常,也可以将ExpectedException属性与异常处理程序一起使用

[ExpectedException(Handler = "HandleException")]

Your test will be 您的测试将是

[Test]
[ExpectedException(Handler = "HandleException")]
public void ExampleTest()
{
    var date = new DateTime(2014, 01, 14);
    throw new InvalidOperationException("Invalid date: " + date.ToString());
}

public void HandleException(Exception ex)
{
    if (!(ex is InvalidOperationException))
        Assert.Fail("Unexpected type of exception thrown by method");

    // Compare expected exception message with ex.Message
    // Assert.Fail if they do not match
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM