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.

 

 

 

 

 

 

 

作者:Chuck Lu    GitHub    
posted @   ChuckLu  阅读(199)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2017-05-31 在IIS中给某一个网站添加binding的坑
2017-05-31 Firefox中使用pac
2017-05-31 火狐浏览器设置bypass
2017-05-31 如何卸载visualsvn for visual studio
2016-05-31 perl的安装
点击右上角即可分享
微信分享提示