NSubstitute
https://github.com/nsubstitute/NSubstitute
http://nsubstitute.github.io/help/creating-a-substitute/
NSubstitute完全手册索引
What's the default value will NSubstitute return for a method? example code in C# and NUnit
In NSubstitute, by default, methods will return default values for reference types (e.g. null
for string
) and default values for value types (e.g. 0
for int
). This means that, by default, methods called on a NSubstitute substitute will return the default value for their return type, unless specifically configured to return a different value. Here is an example in C# using NUnit:
[Test]
public void DefaultReturnValues_Example()
{
// Arrange
var substitute = Substitute.For<IFoo>();
// Act
var result = substitute.Bar();
// Assert
Assert.AreEqual(default(int), result);
}
public interface IFoo
{
int Bar();
}
In this example, IFoo.Bar
returns an int
, so the default value for int
is returned by NSubstitute, which is 0
. You can then set up a return value for the method using substitute.Bar().Returns(...)
to return a specific value.
explain the code
[Test]
public void Analyze_LoggerThrows_CallWebServiceWithNSub()
{
var mockWebService = Substitute.For<IWebService>();
var stubLogger = Substitute.For<ILogger>();
stubLogger.When(logger=>logger.LogError(Arg.Any<string>()))//Simulates exception on any input
.Do(info => throw new Exception("fake exception"));
var analyzer = new LogAnalyzer2(stubLogger, mockWebService);
analyzer.MinNameLength = 10;
analyzer.Analyze("Short.txt");
mockWebService.Received()//Checks that mock web service was called with a string containing "fake exception"
.Write(Arg.Is<string>(s => s.Contains("fake exception")));
}
This is an example of using NSubstitute to write a test for a class named LogAnalyzer2
. The test method Analyze_LoggerThrows_CallWebServiceWithNSub
is testing the behavior of LogAnalyzer2
when a logger throws an exception.
The code sets up a mock implementation of the IWebService
interface using Substitute.For<IWebService>()
, and a stub implementation of the ILogger
interface using Substitute.For<ILogger>()
.
The stub implementation of ILogger
is then set up to throw an exception with the message "fake exception" whenever its LogError
method is called with any argument, by using When(logger=>logger.LogError(Arg.Any<string>()))
and Do(info => throw new Exception("fake exception"))
.
An instance of LogAnalyzer2
is then created, passing the stub logger and mock web service as arguments. The test sets the MinNameLength
property to 10, and calls the Analyze
method with the argument "Short.txt".
The final line of the test uses mockWebService.Received()
and Write(Arg.Is<string>(s => s.Contains("fake exception")))
to verify that the mock web service's Write
method was called with a string that contains the message "fake exception". This verifies that when the Logger
throws an exception, the LogAnalyzer2
class calls the Write
method on the web service with the error message.