NSubstitute 不打印出 NUnit 断言

NSubstitute does not print out NUnit assertion

我刚开始使用 NSubstitute。我主要与 Moq 一起工作,这就是我在做的事情:

// In my unit test on menter code herey mock:
HasLogMessage(Is.EqualTo("expected value"));

private void HasLogMessage(EqualConstraint s)
{
    log.Verify(y => y.Error(It.Is<string>(v => Verify(v, s))));
}

private bool Verify(string s, EqualConstraint equalConstraint)
{
    Assert.That(s, equalConstraint);
    return true;
}

单元测试为运行时的输出。请注意,它告诉我们期望值和实际值是什么:

Expected string length 14 but was 116. Strings differ at index 0.
Expected: "expected value"
But was:  "real value..."
-----------^
 at NUnit.Framework.Assert.That(Object actual, 

IResolveConstraint 表达式,字符串消息,Object[] args)

我希望能够将其与 NSubstitute 模拟一起使用,这是我的尝试:

HasLogMessage(Is.EqualTo("Expected value"));

private void HasLogMessage(EqualConstraint s)
{
    log.Received().Log(LogLevel.Error, Arg.Is<Func<string>>(x => Verify(x, 
}

private bool Verify(Func<string> s, EqualConstraint equalConstraint)
{
    Assert.That(s(), equalConstraint);
    return true;
}

但是这样不输出NUnit断言错误

NSubstitute.Exceptions.ReceivedCallsException : Expected to receive a call matching:
    Log(Error, x => value(IdentityServer3.Saml2Bearer.Tests.Saml2BearerGrantValidatorTest)
.Verify(x, value(IdentityServer3.Saml2Bearer.Tests.Saml2BearerGrantValidatorTest+<>c__DisplayClass21_0).s), <null>, )
Actually received no matching calls.
Received 2 non-matching calls (non-matching arguments indicated 
with '*' characters)

我是不是漏掉了什么?

日志类型澄清后更新:

除了使用 incomplete plumbing mentioned below,对于 Func<string> 我会捕获使用的参数并稍后检查它们。

var log = Substitute.For<ILog>();
var loggedErrors = new List<string>();
// Capture the argument passed to Log whenever LogLevel.Error is called
log.Log (LogLevel.Error, Arg.Do<Func<string>>(x => loggedErrors.Add(x())));

log.Log(LogLevel.Error, () => "the real call...");

Assert.That(loggedErrors, Is.EqualTo (new[] { "expected" }));

/*
NUnit.Framework.AssertionException:   Expected is <System.String[1]>, actual is <System.Collections.Generic.List`1[System.String]> with 1 elements
  Values differ at index [0]
  Expected string length 8 but was 16. Strings differ at index 0.
  Expected: "expected"
  But was:  "the real call..."
  -----------^
*/

原回答:

我们通常会把它写成一个简单的 Received() 断言,它将显示预期值和实际值。

log.Received ().Log (LogLevel.Error, "expected");

/*
Expected to receive a call matching:
    Log(Error, "expected")
Actually received no matching calls.
Received 1 non-matching call (non-matching arguments indicated with '*' characters):
    Log(Error, *"the real call..."*)
*/

如果您想使用断言库进行更具描述性的匹配,NSubstitute 中有一些不完整的管道可以通过一些工作来实现。有an example in this issue.