{"id":94674,"date":"2023-08-01T08:09:08","date_gmt":"2023-08-01T06:09:08","guid":{"rendered":"https:\/\/code-maze.com\/?p=94674"},"modified":"2024-02-26T21:43:53","modified_gmt":"2024-02-26T20:43:53","slug":"csharp-effective-mocking-with-nsubstitute","status":"publish","type":"post","link":"https:\/\/code-maze.com\/csharp-effective-mocking-with-nsubstitute\/","title":{"rendered":"Effective Mocking With NSubstitute in .NET"},"content":{"rendered":"<p>In this article, we will delve into the world of mocking with NSubstitute in .NET and explore how it can help us create comprehensive and efficient tests for our projects.<\/p>\n<div style=\"padding: 20px; border-left: 5px #dc2323 solid; display: block; margin-bottom: 20px; box-shadow: 1px 1px 5px 0px lightgrey;\">To download the source code for this article, you can visit our <a href=\"https:\/\/github.com\/CodeMazeBlog\/CodeMazeGuides\/tree\/main\/dotnet-testing\/MockingWithNSubstitute\/\" target=\"_blank\" rel=\"nofollow noopener\">GitHub repository<\/a>.<\/div>\n<p>Let&#8217;s get into it!<\/p>\n<h2>What Is NSubstitute?<\/h2>\n<p><a href=\"https:\/\/github.com\/nsubstitute\/NSubstitute\" target=\"_blank\" rel=\"nofollow noopener\">NSubstitute<\/a> is a popular mocking framework\u00a0in .NET, similar to <a href=\"https:\/\/code-maze.com\/unit-testing-controllers-aspnetcore-moq\/\" target=\"_blank\" rel=\"noopener\">Moq<\/a>, that simplifies the creation of mock objects for unit testing.<\/p>\n<p><strong>With NSubstitute, we can simulate the behavior of dependencies in our tests.<\/strong> The library provides us with the possibility to define expectations and verify interactions without the need for concrete implementations. This is a powerful tool that allows developers to isolate and test individual components. This leads to more efficient and reliable unit tests and also enhances the overall quality of our applications.<\/p>\n<p><strong>We should be careful when using NSubstitute, as it only works effectively with interfaces or class members that are overridable from the test assembly.<\/strong> When we mock classes with non-<code>virtual<\/code> or <code>internal virtual<\/code> members, there&#8217;s a risk of unintentionally executing real code in our tests, which may lead to unexpected behavior and it is best to avoid it.<\/p>\n<h2>Installing NSubstitute and Setting up Our Code<\/h2>\n<p>The first thing we have to do is install the NuGet package:<\/p>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"raw\">dotnet add package NSubstitute<\/code><\/p>\n<p>It is also good to install <code>NSubstitute.Analyzers.CSharp<\/code> to help us catch potential problems with the usage of NSubstitute in our code:<\/p>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"raw\">dotnet add package NSubstitute.Analyzers.CSharp<\/code><\/p>\n<p>This Roslyn analyzer helps us in such cases when we mock non-<code>virtual<\/code> members as mentioned in the previous section. If you want to know more about how Roslyn analyzer work, we have a <a href=\"https:\/\/code-maze.com\/dotnet-roslyn-compiler-and-analyzers\/\" target=\"_blank\" rel=\"noopener\">separate article about the usage of Roslyn analyzers<\/a>.<\/p>\n<h2>Setting up Our Code<\/h2>\n<p>After that, we create a very simple <code>User<\/code> record:<\/p>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public record User(string Name, string Email);<\/code><\/p>\n<p>Next, let&#8217;s create an interface of a service that will send emails but without an implementation:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public interface IEmailService\r\n{\r\n    bool IsValidEmail(string email);\r\n    bool SendEmail(string recipient, string subject, string message);\r\n}<\/pre>\n<p>Then, we define the <code>INotificationService<\/code> interface:\u00a0<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public interface INotificationService\r\n{\r\n    bool NotifyUser(User user, string message);\r\n}<\/pre>\n<p>And finally, its implementation:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public class NotificationService : INotificationService\r\n{\r\n    private readonly IEmailService _emailService;\r\n\r\n    public NotificationService(IEmailService emailService)\r\n    {\r\n        _emailService = emailService;\r\n    }\r\n\r\n    public bool NotifyUser(User user, string message)\r\n    {\r\n        if (!_emailService.IsValidEmail(user.Email) ||\r\n            string.IsNullOrWhiteSpace(message))\r\n        {\r\n            return false;\r\n        }\r\n\r\n        var sentSuccessfully = _emailService.SendEmail(user.Email, \"Notification from CodeMaze\", message);\r\n\r\n        return sentSuccessfully;\r\n    }\r\n}<\/pre>\n<p>The <code>NotificationService<\/code> class is implementing the <code>INotificationService<\/code> interface and uses an injected <code>IEmailService<\/code> to send email notifications.<\/p>\n<h2>Mocking With NSubstitute<\/h2>\n<p>To properly test our <code>NotificationService<\/code> class, we need to be able to mock and have complete control over our <code>IEmailService<\/code> interface. We&#8217;ll see how we can achieve that by using NSubstitute.<\/p>\n<h3>Mocking an Object With NSubstitute<\/h3>\n<p>With NSubstitute, it is easy for us to mock an object:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\" data-enlighter-highlight=\"10\">public class NotificationServiceTests\r\n{\r\n    private readonly User _user;\r\n    private readonly IEmailService _emailService;\r\n    private readonly NotificationService _notificationService;\r\n\r\n    public NotificationServiceTests()\r\n    {\r\n        _user = new User(\"Code-Maze\", \"email@code-maze.com\");\r\n        _emailService = Substitute.For&lt;IEmailService&gt;();\r\n        _notificationService = new NotificationService(_emailService);\r\n    }\r\n}\t<\/pre>\n<p>We create the <code>NotificationServiceTests<\/code> class which is responsible for testing the <code>NotificationService<\/code> class. Within the test class, we create a <code>User<\/code> and a substitute\/mock object of type <code>IEmailService<\/code> using NSubstitute&#8217;s <code>Substitute.For&lt;T&gt;()<\/code> method, which allows us to simulate the behavior of the actual <code>IEmailService<\/code> dependency.<\/p>\n<p>We then inject the substitute into the constructor of <code>NotificationService<\/code> to create a new instance and assign it to <code>_notificationService<\/code>. By doing this, we can isolate the <code>NotificationService<\/code> class and verify its interactions with the substituted <code>IEmailService<\/code> during our testing.<\/p>\n<h3>Mocking Behaviors and Return Values With NSubstitute<\/h3>\n<p>For any mocking library, it&#8217;s vital to be able to mock behaviors and return values:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\" data-enlighter-highlight=\"6-9\">[Fact]\r\npublic void GivenInputIsCorrect_WhenNotifyUserIsInvoked_ThenTrueIsReturned()\r\n{\r\n    \/\/ Arrange\r\n    const string message = \"Mocking behaviors and expectations with NSubstitute\";\r\n    _emailService.IsValidEmail(_user.Email)\r\n        .Returns(true);\r\n    _emailService.SendEmail(_user.Email, \"Notification from CodeMaze\", message)\r\n        .Returns(true);\r\n\r\n    \/\/ Act\r\n    var result = _notificationService.NotifyUser(_user, message);\r\n\r\n    \/\/ Assert\r\n    result.Should().BeTrue();\r\n}<\/pre>\n<p>We create a test method to verify the <code>NotifyUser()<\/code> method&#8217;s behavior when the input is correct.<\/p>\n<p>First, we set up the required dependencies by creating\u00a0a <code>message<\/code>. Then, we use NSubstitute to simulate the <code>IsValidEmail()<\/code> and <code>SendEmail()<\/code> methods&#8217; behaviors of the <code>_emailService<\/code> mock object. We achieve that by calling both methods as we usually would and then calling the NSubstitute&#8217;s <code>Return()<\/code> method.\u00a0 We also pass <code>true<\/code> both times to indicate that the email is valid and was sent successfully.<\/p>\n<p>Next, we invoke the <code>NotifyUser()<\/code> method with the test data. Finally, we assert the result using the FluentAssertions library to ensure that the method returns <code>true<\/code>, indicating that the email was successfully sent.<\/p>\n<h3>Ignoring or Conditionally Matching Arguments<\/h3>\n<p>With NSubstitute we can use argument matcher:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\" data-enlighter-highlight=\"6-9\">[Fact]\r\npublic void GivenInputIsNotCorrect_WhenNotifyUserIsInvoked_ThenFalseIsReturned()\r\n{\r\n    \/\/ Arrange\r\n    const string message = \"Ignoring or Conditionally Matching Arguments\";\r\n    _emailService.IsValidEmail(default)\r\n        .ReturnsForAnyArgs(false);\r\n    _emailService.SendEmail(Arg.Any&lt;string&gt;(), Arg.Is&lt;string&gt;(x =&gt; x.Length &gt; 5), message)\r\n        .Returns(true);\r\n\r\n    \/\/ Act\r\n    var result = _notificationService.NotifyUser(_user, message);\r\n\r\n    \/\/ Assert\r\n    result.Should().BeFalse();\r\n}<\/pre>\n<p>We create another test method to verify the <code>NotifyUser()<\/code> method&#8217;s behavior when the input is not correct. Then, we set the dependencies and move on to configuring the <code>_emailService<\/code> methods&#8217; behaviors.<\/p>\n<p>We start with the <code>IsValidEmail()<\/code> method and want to return <code>false<\/code> in any case to indicate that every email address will be invalid. For that, we pass <code>default<\/code> as an argument, this way any <code>string<\/code> value will match. Then we follow up with the <code>ReturnsForAnyArgs()<\/code> method, indicating that no matter what argument we have the method should always return <code>false<\/code>.<\/p>\n<p>Then, we set up the <code>SendEmail()<\/code> method to always return <code>true<\/code>. For the first argument, we use <code>Arg.Any&lt;T&gt;()<\/code> method, where <code>T<\/code> is a <code>string<\/code>. This is identical to the <code>default<\/code> approach we used previously and will match any <code>string<\/code>. Then we use <code>Arg.Is&lt;string&gt;(x =&gt; x.Length &gt; 5)<\/code> to indicate that we should match any <code>string<\/code> that is longer than five characters. For the final argument, we just use the <code>message<\/code> variable.<\/p>\n<p>Finally, we invoke the <code>NotifyUser()<\/code> method and assert that its result is <code>false<\/code>, indicating that our code didn&#8217;t send the email due to incorrect input.<\/p>\n<h3>Verifying Mock Interactions<\/h3>\n<p>We can use NSubstitute to check if we call a method or not:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\" data-enlighter-highlight=\"16-17\">[Fact]\r\npublic void GivenInputIsNotCorrect_WhenNotifyUserIsInvoked_ThenFalseIsReturned()\r\n{\r\n    \/\/ Arrange\r\n    const string message = \"Ignoring or Conditionally Matching Arguments\";\r\n    _emailService.IsValidEmail(default)\r\n        .ReturnsForAnyArgs(false);\r\n    _emailService.SendEmail(Arg.Any&lt;string&gt;(), Arg.Is&lt;string&gt;(x =&gt; x.Length &gt; 5), message)\r\n        .Returns(true);\r\n\r\n    \/\/ Act\r\n    var result = _notificationService.NotifyUser(_user, message);\r\n\r\n    \/\/ Assert\r\n    result.Should().BeFalse();\r\n    _emailService.Received(1).IsValidEmail(Arg.Any&lt;string&gt;());\r\n    _emailService.DidNotReceive().SendEmail(Arg.Any&lt;string&gt;(), Arg.Is&lt;string&gt;(x =&gt; x.Length &gt; 5), message);\r\n}<\/pre>\n<p>We update the test method from the previous section by checking whether or not we call the <code>_emailService<\/code> methods. The way we do this is by calling the <code>Received()<\/code> method on the <code>_emailService<\/code> instance and then the method we want to check.<\/p>\n<p>First, we verify that we call the <code>IsValidEmail()<\/code> method exactly once with any <code>string<\/code> argument.\u00a0 We can also use the <code>Received()<\/code> method without passing any arguments which will assert if the method in question is called at least once.<\/p>\n<p>We can also verify that we don&#8217;t call a method by using the <code>DidNotReceive()<\/code> method. With it, we verify that the <code>NotifyUser()<\/code> method doesn&#8217;t call the <code>SendEmail()<\/code> method as is not supposed to when <code>IsValidEmail()<\/code> returns <code>false<\/code>.<\/p>\n<p>We can use this to ensure that the expected interactions between the <code>NotificationService<\/code> and <code>_emailService<\/code> are met during the unit test scenario.<\/p>\n<h3>Throwing Exceptions When Mocking With NSubstitute<\/h3>\n<p>We can use NSubstitute to specify that a method should throw an <code>Exception<\/code>. First, we update our <code>NotifyUser()<\/code> method:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\" data-enlighter-highlight=\"9-19\">public bool NotifyUser(User user, string message)\r\n{\r\n    if (!_emailService.IsValidEmail(user.Email) ||\r\n        string.IsNullOrWhiteSpace(message))\r\n    {\r\n        return false;\r\n    }\r\n\r\n    try\r\n    {\r\n        var sentSuccessfully = _emailService\r\n            .SendEmail(user.Email, \"Notification from CodeMaze\", message);\r\n\r\n        return sentSuccessfully;\r\n    }\r\n    catch\r\n    {\r\n        throw;\r\n    }\r\n}<\/pre>\n<p>We wrap the <code>SendEmail()<\/code> method in a <code>try<\/code>&#8211;<code>catch<\/code> statement and re-throw if an <code>Exception<\/code> is caught.<\/p>\n<p>Then, let&#8217;s write our test method:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\" data-enlighter-highlight=\"8-9\">[Fact]\r\npublic void GivenExceptionIsThrown_WhenNotifyUserIsInvoked_ThenFalseIsReturned()\r\n{\r\n    \/\/ Arrange\r\n    const string message = \"Throwing Exceptions When Mocking With NSubstitute\";\r\n    _emailService.IsValidEmail(_user.Email)\r\n        .Returns(true);\r\n    _emailService.SendEmail(_user.Email, \"Notification from CodeMaze\", message)\r\n        .Returns(x =&gt; { throw new InvalidEmailException(); });\r\n\r\n    \/\/ Act\r\n    var act = () =&gt; _notificationService.NotifyUser(_user, message);\r\n\r\n    \/\/ Assert\r\n    act.Should().ThrowExactly&lt;InvalidEmailException&gt;();\r\n}<\/pre>\n<p>We set up the behavior of the <code>SendEmail()<\/code> method using the NSubstitute&#8217;s <code>Return()<\/code> method. For a return value of the method, we use the <code>x =&gt; { throw new InvalidEmailException(); }<\/code> lambda expression which states that a custom <code>InvalidEmailException<\/code> should be thrown. Then, we call the <code>NotifyUser()<\/code> method and assert that it throws an <code>InvalidEmailException<\/code> as well. This approach works only for non-<code>void<\/code> methods.<\/p>\n<p>But there is an alternative and better solution for this scenario:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\" data-enlighter-highlight=\"8-9\">[Fact]\r\npublic void GivenExceptionIsThrown_WhenNotifyUserIsInvoked_ThenFalseIsReturned()\r\n{\r\n    \/\/ Arrange\r\n    const string message = \"Throwing Exceptions When Mocking With NSubstitute\";\r\n    _emailService.IsValidEmail(_user.Email)\r\n        .Returns(true);\r\n    _emailService.When(x =&gt; x.SendEmail(_user.Email, \"Notification from CodeMaze\", message))\r\n        .Do(x =&gt; { throw new InvalidEmailException(); });\r\n\r\n    \/\/ Act\r\n    var act = () =&gt; _notificationService.NotifyUser(_user, message);\r\n\r\n    \/\/ Assert\r\n    act.Should().ThrowExactly&lt;InvalidEmailException&gt;();\r\n}<\/pre>\n<p>We update the same test method by configuring the <code>SendEmail()<\/code> method using NSubstitute&#8217;s <code>When()<\/code> and <code>Do()<\/code> methods. We pass lambda expressions to both methods. To the <code>When()<\/code> method, we pass the <code>SendEmail()<\/code> method with the expected arguments. For the <code>Do()<\/code> method we use the same error-throwing lambda from the previous example. This approach will work for both <code>void<\/code> and non-<code>void<\/code> methods.<\/p>\n<h2>Conclusion<\/h2>\n<p>In this article, we delved into the world of mocking with NSubstitute in .NET, exploring its powerful capabilities for creating comprehensive and efficient tests.<\/p>\n<p>NSubstitute simplifies the process of creating mock objects, allowing us to simulate dependencies&#8217; behaviors and return values, and verifying interactions with ease. By effectively isolating and testing individual components, NSubstitute helps us enhance the reliability and overall quality of our applications. However, we must be cautious when using NSubstitute, especially with classes, to avoid unintended execution of real code in our tests.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this article, we will delve into the world of mocking with NSubstitute in .NET and explore how it can help us create comprehensive and efficient tests for our projects. Let&#8217;s get into it! What Is NSubstitute? NSubstitute is a popular mocking framework\u00a0in .NET, similar to Moq, that simplifies the creation of mock objects for [&hellip;]<\/p>\n","protected":false},"author":6,"featured_media":62189,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_et_pb_use_builder":"","_et_pb_old_content":"","_et_gb_content_width":"","footnotes":""},"categories":[12,1112],"tags":[1811,1262,1337,1890,173],"class_list":["post-94674","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-csharp","category-testing","tag-c","tag-mock","tag-mocking","tag-nsubstitute","tag-unit-testing","et-has-post-format-content","et_post_format-et-post-format-standard"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v24.7 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Effective Mocking With NSubstitute in .NET - Code Maze<\/title>\n<meta name=\"description\" content=\"In this article, we will delve into the world of mocking with NSubstitute in .NET and explore how it can help us create comprehensive tests.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/code-maze.com\/csharp-effective-mocking-with-nsubstitute\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Effective Mocking With NSubstitute in .NET - Code Maze\" \/>\n<meta property=\"og:description\" content=\"In this article, we will delve into the world of mocking with NSubstitute in .NET and explore how it can help us create comprehensive tests.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/code-maze.com\/csharp-effective-mocking-with-nsubstitute\/\" \/>\n<meta property=\"og:site_name\" content=\"Code Maze\" \/>\n<meta property=\"article:published_time\" content=\"2023-08-01T06:09:08+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2024-02-26T20:43:53+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png\" \/>\n\t<meta property=\"og:image:width\" content=\"1100\" \/>\n\t<meta property=\"og:image:height\" content=\"620\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"Code Maze\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@https:\/\/twitter.com\/CodeMazeBlog\" \/>\n<meta name=\"twitter:site\" content=\"@CodeMazeBlog\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Code Maze\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"6 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":[\"Article\",\"BlogPosting\"],\"@id\":\"https:\/\/code-maze.com\/csharp-effective-mocking-with-nsubstitute\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/code-maze.com\/csharp-effective-mocking-with-nsubstitute\/\"},\"author\":{\"name\":\"Code Maze\",\"@id\":\"https:\/\/code-maze.com\/#\/schema\/person\/09d29b223012c8e94a68ba62861d0b04\"},\"headline\":\"Effective Mocking With NSubstitute in .NET\",\"datePublished\":\"2023-08-01T06:09:08+00:00\",\"dateModified\":\"2024-02-26T20:43:53+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/code-maze.com\/csharp-effective-mocking-with-nsubstitute\/\"},\"wordCount\":1156,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\/\/code-maze.com\/#organization\"},\"image\":{\"@id\":\"https:\/\/code-maze.com\/csharp-effective-mocking-with-nsubstitute\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png\",\"keywords\":[\"C#\",\"Mock\",\"Mocking\",\"NSubstitute\",\"Unit Testing\"],\"articleSection\":[\"C#\",\"Testing\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/code-maze.com\/csharp-effective-mocking-with-nsubstitute\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/code-maze.com\/csharp-effective-mocking-with-nsubstitute\/\",\"url\":\"https:\/\/code-maze.com\/csharp-effective-mocking-with-nsubstitute\/\",\"name\":\"Effective Mocking With NSubstitute in .NET - Code Maze\",\"isPartOf\":{\"@id\":\"https:\/\/code-maze.com\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/code-maze.com\/csharp-effective-mocking-with-nsubstitute\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/code-maze.com\/csharp-effective-mocking-with-nsubstitute\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png\",\"datePublished\":\"2023-08-01T06:09:08+00:00\",\"dateModified\":\"2024-02-26T20:43:53+00:00\",\"description\":\"In this article, we will delve into the world of mocking with NSubstitute in .NET and explore how it can help us create comprehensive tests.\",\"breadcrumb\":{\"@id\":\"https:\/\/code-maze.com\/csharp-effective-mocking-with-nsubstitute\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/code-maze.com\/csharp-effective-mocking-with-nsubstitute\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/code-maze.com\/csharp-effective-mocking-with-nsubstitute\/#primaryimage\",\"url\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png\",\"contentUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png\",\"width\":1100,\"height\":620,\"caption\":\"C# Development\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/code-maze.com\/csharp-effective-mocking-with-nsubstitute\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/code-maze.com\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Effective Mocking With NSubstitute in .NET\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/code-maze.com\/#website\",\"url\":\"https:\/\/code-maze.com\/\",\"name\":\"Code Maze\",\"description\":\"Learn. Code. Succeed.\",\"publisher\":{\"@id\":\"https:\/\/code-maze.com\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/code-maze.com\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/code-maze.com\/#organization\",\"name\":\"Code Maze\",\"url\":\"https:\/\/code-maze.com\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/code-maze.com\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez.png\",\"contentUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez.png\",\"width\":3511,\"height\":3510,\"caption\":\"Code Maze\"},\"image\":{\"@id\":\"https:\/\/code-maze.com\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/x.com\/CodeMazeBlog\"]},{\"@type\":\"Person\",\"@id\":\"https:\/\/code-maze.com\/#\/schema\/person\/09d29b223012c8e94a68ba62861d0b04\",\"name\":\"Code Maze\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/code-maze.com\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez-150x150.png\",\"contentUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez-150x150.png\",\"caption\":\"Code Maze\"},\"description\":\"This is the standard author on the site. Most articles are published by individual authors, with their profiles, but when several authors have contributed, we publish collectively as a part of this profile.\",\"sameAs\":[\"https:\/\/www.linkedin.com\/company\/codemaze\/\",\"https:\/\/x.com\/https:\/\/twitter.com\/CodeMazeBlog\"],\"url\":\"https:\/\/code-maze.com\/author\/codemazecontributor\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Effective Mocking With NSubstitute in .NET - Code Maze","description":"In this article, we will delve into the world of mocking with NSubstitute in .NET and explore how it can help us create comprehensive tests.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/code-maze.com\/csharp-effective-mocking-with-nsubstitute\/","og_locale":"en_US","og_type":"article","og_title":"Effective Mocking With NSubstitute in .NET - Code Maze","og_description":"In this article, we will delve into the world of mocking with NSubstitute in .NET and explore how it can help us create comprehensive tests.","og_url":"https:\/\/code-maze.com\/csharp-effective-mocking-with-nsubstitute\/","og_site_name":"Code Maze","article_published_time":"2023-08-01T06:09:08+00:00","article_modified_time":"2024-02-26T20:43:53+00:00","og_image":[{"width":1100,"height":620,"url":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png","type":"image\/png"}],"author":"Code Maze","twitter_card":"summary_large_image","twitter_creator":"@https:\/\/twitter.com\/CodeMazeBlog","twitter_site":"@CodeMazeBlog","twitter_misc":{"Written by":"Code Maze","Est. reading time":"6 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":["Article","BlogPosting"],"@id":"https:\/\/code-maze.com\/csharp-effective-mocking-with-nsubstitute\/#article","isPartOf":{"@id":"https:\/\/code-maze.com\/csharp-effective-mocking-with-nsubstitute\/"},"author":{"name":"Code Maze","@id":"https:\/\/code-maze.com\/#\/schema\/person\/09d29b223012c8e94a68ba62861d0b04"},"headline":"Effective Mocking With NSubstitute in .NET","datePublished":"2023-08-01T06:09:08+00:00","dateModified":"2024-02-26T20:43:53+00:00","mainEntityOfPage":{"@id":"https:\/\/code-maze.com\/csharp-effective-mocking-with-nsubstitute\/"},"wordCount":1156,"commentCount":0,"publisher":{"@id":"https:\/\/code-maze.com\/#organization"},"image":{"@id":"https:\/\/code-maze.com\/csharp-effective-mocking-with-nsubstitute\/#primaryimage"},"thumbnailUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png","keywords":["C#","Mock","Mocking","NSubstitute","Unit Testing"],"articleSection":["C#","Testing"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/code-maze.com\/csharp-effective-mocking-with-nsubstitute\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/code-maze.com\/csharp-effective-mocking-with-nsubstitute\/","url":"https:\/\/code-maze.com\/csharp-effective-mocking-with-nsubstitute\/","name":"Effective Mocking With NSubstitute in .NET - Code Maze","isPartOf":{"@id":"https:\/\/code-maze.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/code-maze.com\/csharp-effective-mocking-with-nsubstitute\/#primaryimage"},"image":{"@id":"https:\/\/code-maze.com\/csharp-effective-mocking-with-nsubstitute\/#primaryimage"},"thumbnailUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png","datePublished":"2023-08-01T06:09:08+00:00","dateModified":"2024-02-26T20:43:53+00:00","description":"In this article, we will delve into the world of mocking with NSubstitute in .NET and explore how it can help us create comprehensive tests.","breadcrumb":{"@id":"https:\/\/code-maze.com\/csharp-effective-mocking-with-nsubstitute\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/code-maze.com\/csharp-effective-mocking-with-nsubstitute\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/code-maze.com\/csharp-effective-mocking-with-nsubstitute\/#primaryimage","url":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png","contentUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png","width":1100,"height":620,"caption":"C# Development"},{"@type":"BreadcrumbList","@id":"https:\/\/code-maze.com\/csharp-effective-mocking-with-nsubstitute\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/code-maze.com\/"},{"@type":"ListItem","position":2,"name":"Effective Mocking With NSubstitute in .NET"}]},{"@type":"WebSite","@id":"https:\/\/code-maze.com\/#website","url":"https:\/\/code-maze.com\/","name":"Code Maze","description":"Learn. Code. Succeed.","publisher":{"@id":"https:\/\/code-maze.com\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/code-maze.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/code-maze.com\/#organization","name":"Code Maze","url":"https:\/\/code-maze.com\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/code-maze.com\/#\/schema\/logo\/image\/","url":"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez.png","contentUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez.png","width":3511,"height":3510,"caption":"Code Maze"},"image":{"@id":"https:\/\/code-maze.com\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/x.com\/CodeMazeBlog"]},{"@type":"Person","@id":"https:\/\/code-maze.com\/#\/schema\/person\/09d29b223012c8e94a68ba62861d0b04","name":"Code Maze","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/code-maze.com\/#\/schema\/person\/image\/","url":"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez-150x150.png","contentUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez-150x150.png","caption":"Code Maze"},"description":"This is the standard author on the site. Most articles are published by individual authors, with their profiles, but when several authors have contributed, we publish collectively as a part of this profile.","sameAs":["https:\/\/www.linkedin.com\/company\/codemaze\/","https:\/\/x.com\/https:\/\/twitter.com\/CodeMazeBlog"],"url":"https:\/\/code-maze.com\/author\/codemazecontributor\/"}]}},"_links":{"self":[{"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/posts\/94674","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/users\/6"}],"replies":[{"embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/comments?post=94674"}],"version-history":[{"count":6,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/posts\/94674\/revisions"}],"predecessor-version":[{"id":109693,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/posts\/94674\/revisions\/109693"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/media\/62189"}],"wp:attachment":[{"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/media?parent=94674"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/categories?post=94674"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/tags?post=94674"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}