2015-11-20 62 views
0

我刚开始使用NSubstitute。我大多用Moq工作,这是我在做什么:NSubstitute不打印出NUnit声明

// 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表达,字符串消息,

我希望能够使用与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) 

我在这里错过了什么吗?日志型澄清后

回答

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

+0

你的例子不适合在这里,第二个参数不是一个字符串,它是'Func '。我想这样做是行不通的,因为NSubstitute不会评价我的第二个,它只会说接收到一个非maatching的调用,其中第二个param是一个不同的函数。 (LogLevel.Error,()=>“expected”);'Log.Received().Log(LogLevel.Error, – Darius