NSubstitute不会打印出NUnit断言

时间:2015-11-20 13:33:15

标签: c# unit-testing nsubstitute

我刚开始使用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表达式,String消息,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)

我在这里错过了什么吗?

1 个答案:

答案 0 :(得分:0)

日志类型说明后

更新:

除了使用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