NSubstitute:当字符串来自资源时,Received() 不检查字符串参数

NSubstitute: Received() does not check string parameter when string comes from resource

我使用 NSubstitute for my NUnit 测试并尝试检查是否使用正确的值调用方法。直到知道一切正常。我必须本地化文本,因此为此使用资源字符串。现在每个单元测试都失败了,测试要接收的方法,其中字符串参数包含一个新行。

这是一个简化的例子:

// Old Version, where the unit test succeed
public void CallWithText(ICallable callable)
{
    callable.ShowText("Some text with a new\nline."); 
}

// New Version, where the unit test fails
// Text of `Properties.Resources.TextWithNewLine` in the
// Resources.resx is "Some text with a new
// line."
public void CallWithText(ICallable callable)
{
    callable.ShowText(Properties.Resources.TextWithNewLine); 
}

[Test]
public void CallWithText_WhenCalled_CallsCallable()
{
    var caller = new Caller();
    var callable = Substitute.For<ICallable>();

    caller.CallWithText(callable);

    callable.Received(1).ShowText("Some text with a new\nline.");
}

在我看来,新线路有问题。有没有人有解决方案,因为适应所有单元测试是一团糟。

在单元测试中比较精确的字符串会增加更多的维护工作。
在您的情况下,new line 在不同的执行环境中可能会有所不同。

对于字符串,我建议使用 Contains 方法断言传递的参数。在哪里可以查看更重要的词

[Test]
public void CallWithText_WhenCalled_CallsCallable()
{
    var caller = new Caller();
    var callable = Substitute.For<ICallable>();

    caller.CallWithText(callable);

    callable.Received(1).ShowText(Arg.Is<string>(text => text.Contains("Some text")));
}

这表示与Properties.Resources.TextWithNewLine"Some text with a new\nline."不同。在不太了解 Properties.Resources.TextWithNewLine 的情况下,我建议您尝试将测试更改为

[Test]
public void CallWithText_WhenCalled_CallsCallable()
{
    var caller = new Caller();
    var callable = Substitute.For<ICallable>();

    caller.CallWithText(callable);

    callable.Received(1).ShowText(Arg.Any<string>());
}

或者如果你真的想断言字符串的内容,请使用实际的字符串,更改为(确保资源文件在测试项目中)

[Test]
public void CallWithText_WhenCalled_CallsCallable()
{
    var caller = new Caller();
    var callable = Substitute.For<ICallable>();

    caller.CallWithText(callable);

    callable.Received(1).ShowText(Properties.Resources.TextWithNewLine);
}

问题与 NSubstitute 无关,而与 String 本身有关。新的线条符号不仅仅是 \n。它是特定于环境的:\r\n 在 Windows 上,\n 在 Unix 上,\r 在早期的 Mac 操作系统上。请使用 Shift+Enter 在资源管理器中正确添加新行。

您有两种使用方式:

  1. Environment.NewLine 属性 知道当前环境的换行符号:

    callable.Received(1).ShowText("Some text with a new" + Environment.NewLine + "line.");
    
  2. 在预期的字符串中使用明确的换行符:

    callable.Received(1).ShowText(@"Some text with a new
    line.");