{"id":1989,"date":"2024-11-01T08:54:39","date_gmt":"2024-11-01T06:54:39","guid":{"rendered":"https:\/\/epicmarketing.co.il\/notebook\/?p=1989"},"modified":"2024-11-01T09:16:37","modified_gmt":"2024-11-01T07:16:37","slug":"testing","status":"publish","type":"post","link":"https:\/\/epicmarketing.co.il\/notebook\/testing\/","title":{"rendered":"Testing"},"content":{"rendered":"\n<h2 class=\"wp-block-heading\">Learning Objectives<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Understand the importance of <strong>unit testing<\/strong>, <strong>mocking<\/strong>, and <strong>integration testing<\/strong> in ASP.NET Core applications.<\/li>\n\n\n\n<li>Learn how to write <strong>unit tests<\/strong> for controllers, services, and repository classes using tools like <strong>xUnit<\/strong> or <strong>NUnit<\/strong>.<\/li>\n\n\n\n<li>Use <strong>Moq<\/strong> to <strong>mock database interactions<\/strong> for isolated testing.<\/li>\n\n\n\n<li>Learn how to create <strong>integration tests<\/strong> to validate end-to-end functionality of your APIs.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Unit Testing<\/strong><\/h2>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>What is Unit Testing?<\/strong> <strong>Unit testing<\/strong> is the process of testing small, isolated pieces of code (units), such as methods in a class, to ensure they work as expected. The primary goal of unit testing is to verify that individual units of code function correctly in isolation.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In ASP.NET Core, unit testing is often done for:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Controllers<\/strong>: To verify the correct response.<\/li>\n\n\n\n<li><strong>Services<\/strong>: To ensure business logic works correctly.<\/li>\n\n\n\n<li><strong>Repositories<\/strong>: To ensure data fetching and processing is correct.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Tools Used<\/strong>:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>xUnit<\/strong> or <strong>NUnit<\/strong>: Popular testing frameworks used in .NET.<\/li>\n\n\n\n<li><strong>Moq<\/strong>: A mocking library that helps create mock objects for dependencies.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Example: Unit Testing a Service<\/strong>: Here, we test a service method that fetches a product by ID.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\nusing Xunit;\nusing Moq;\n\npublic class ProductServiceTests\n{\n    &#x5B;Fact]\n    public void GetProductById_ShouldReturnProduct_WhenProductExists()\n    {\n        \/\/ Arrange\n        var mockRepo = new Mock&lt;IProductRepository&gt;();\n        mockRepo.Setup(repo =&gt; repo.GetProductById(1))\n                .Returns(new Product { Id = 1, Name = &quot;Laptop&quot;, Price = 1000 });\n\n        var productService = new ProductService(mockRepo.Object);\n\n        \/\/ Act\n        var product = productService.GetProductById(1);\n\n        \/\/ Assert\n        Assert.NotNull(product);\n        Assert.Equal(1, product.Id);\n        Assert.Equal(&quot;Laptop&quot;, product.Name);\n    }\n}\n<\/pre><\/div>\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Moq<\/strong>: We use Moq to <strong>mock<\/strong> the <code>IProductRepository<\/code>, allowing us to test the service independently of the database.<\/li>\n\n\n\n<li><strong>xUnit<\/strong>: The <code>[Fact]<\/code> attribute indicates that this is a unit test.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Real-Life Example<\/strong>: In an <strong>e-commerce<\/strong> system, you may unit test the service that retrieves product information to ensure it handles valid and invalid IDs appropriately.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Mocking Database Interactions<\/strong><\/h2>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Why Mock Database Interactions?<\/strong> Testing code that interacts directly with a database can be complex and slow. Mocking allows us to <strong>isolate the unit of work<\/strong> and simulate database interactions without actually accessing a database.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Using Moq for Repository Mocking<\/strong>:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Moq<\/strong> is a popular library used to create mock versions of dependencies for testing.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Example: Mocking a Repository<\/strong>: Suppose we have a <code>ProductService<\/code> that interacts with a repository. We mock the repository to test the <code>AddProduct<\/code> method.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\npublic class ProductServiceTests\n{\n    &#x5B;Fact]\n    public void AddProduct_ShouldCallAddMethodOnce()\n    {\n        \/\/ Arrange\n        var mockRepo = new Mock&lt;IProductRepository&gt;();\n        var productService = new ProductService(mockRepo.Object);\n        var product = new Product { Id = 1, Name = &quot;Laptop&quot;, Price = 1500.0m };\n\n        \/\/ Act\n        productService.AddProduct(product);\n\n        \/\/ Assert\n        mockRepo.Verify(repo =&gt; repo.AddProduct(product), Times.Once);\n    }\n}\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\"><strong>Verify<\/strong>: The <code>Verify()<\/code> method checks if the <code>AddProduct<\/code> method of the repository was called <strong>exactly once<\/strong>, ensuring correct interaction.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Real-Life Example<\/strong>: In a <strong>financial application<\/strong>, you might mock a service to ensure that adding a new transaction correctly calls the repository.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Integration Testing<\/strong><\/h2>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>What is Integration Testing?<\/strong> <strong>Integration testing<\/strong> is used to verify that multiple components work together as expected. Unlike unit tests, which focus on isolated units of code, integration tests focus on end-to-end behavior, including database, services, and API endpoints.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>ASP.NET Core Integration Testing with TestServer<\/strong>:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>ASP.NET Core provides tools to create integration tests using <code>WebApplicationFactory<\/code> and <code>TestServer<\/code>.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Example: Integration Test for a Product API<\/strong>: This test ensures that the product API works as expected.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\nusing System.Net.Http;\nusing System.Threading.Tasks;\nusing Microsoft.AspNetCore.Mvc.Testing;\nusing Xunit;\n\npublic class ProductApiIntegrationTests : IClassFixture&lt;WebApplicationFactory&lt;Program&gt;&gt;\n{\n    private readonly HttpClient _client;\n\n    public ProductApiIntegrationTests(WebApplicationFactory&lt;Program&gt; factory)\n    {\n        _client = factory.CreateClient();\n    }\n\n    &#x5B;Fact]\n    public async Task GetProductById_ShouldReturnProduct_WhenProductExists()\n    {\n        \/\/ Arrange\n        var productId = 1;\n\n        \/\/ Act\n        var response = await _client.GetAsync($&quot;\/api\/products\/{productId}&quot;);\n\n        \/\/ Assert\n        response.EnsureSuccessStatusCode();\n        var responseBody = await response.Content.ReadAsStringAsync();\n        Assert.Contains(&quot;Laptop&quot;, responseBody);\n    }\n}\n<\/pre><\/div>\n\n\n<ul class=\"wp-block-list\">\n<li><strong><code>WebApplicationFactory&lt;Program><\/code><\/strong>: Sets up the application for testing, allowing the use of real HTTP calls without starting an external server.<\/li>\n\n\n\n<li><strong><code>HttpClient<\/code><\/strong>: Used to make requests to the API endpoints and verify the response.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Real-Life Example<\/strong>: In a <strong>user management system<\/strong>, you could create an integration test to validate the entire process of creating a new user, fetching user details, and ensuring all the endpoints work together.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Where to Keep Testing Files in an ASP.NET Core Project?<\/strong><\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">In an ASP.NET Core project, it's best to organize your tests separately from the main application code. Typically, you keep testing files in a <strong>separate test project<\/strong> within the solution. Here are the recommended folder structures:<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><strong>1. Create a Separate Test Project<\/strong><\/h4>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Unit Tests<\/strong> and <strong>Integration Tests<\/strong> are usually kept in a <strong>separate test project<\/strong>. This approach ensures a clear separation between application code and testing code.<\/li>\n\n\n\n<li>You can create multiple test projects for different kinds of tests. For example:\n<ul class=\"wp-block-list\">\n<li><code>MyApp.Tests.Unit<\/code>: Contains unit tests.<\/li>\n\n\n\n<li><code>MyApp.Tests.Integration<\/code>: Contains integration tests.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n\n\n\n<h4 class=\"wp-block-heading\"><strong>2. Folder Structure for Tests<\/strong><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">If you create a test project, your solution might look like this:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: bash; title: ; notranslate\" title=\"\">\nMyApp\/\n  \u251c\u2500\u2500 Controllers\/\n  \u251c\u2500\u2500 Models\/\n  \u251c\u2500\u2500 Services\/\n  \u251c\u2500\u2500 Repositories\/\n  \u2514\u2500\u2500 Program.cs\n\nMyApp.Tests.Unit\/\n  \u251c\u2500\u2500 Controllers\/\n  \u2502    \u251c\u2500\u2500 ProductControllerTests.cs\n  \u251c\u2500\u2500 Services\/\n  \u2502    \u251c\u2500\u2500 ProductServiceTests.cs\n  \u251c\u2500\u2500 Repositories\/\n  \u2502    \u251c\u2500\u2500 ProductRepositoryTests.cs\n\nMyApp.Tests.Integration\/\n  \u251c\u2500\u2500 IntegrationTests\/\n  \u2502    \u251c\u2500\u2500 ProductApiIntegrationTests.cs\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\"><strong>Explanation<\/strong>:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>MyApp.Tests.Unit<\/strong>: Contains all unit tests. You can organize tests into folders that reflect the structure of the main project. For instance, if you are testing <code>ProductService<\/code>, it should be placed in a <code>Services<\/code> folder in the test project.<\/li>\n\n\n\n<li><strong>MyApp.Tests.Integration<\/strong>: Contains integration tests to validate end-to-end workflows.<\/li>\n<\/ul>\n\n\n\n<h4 class=\"wp-block-heading\"><strong>Creating a Test Project in Visual Studio<\/strong><\/h4>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Right-click the Solution<\/strong> in Solution Explorer.<\/li>\n\n\n\n<li>Select <strong>Add<\/strong> > <strong>New Project<\/strong>.<\/li>\n\n\n\n<li>Choose <strong>xUnit Test Project<\/strong> or <strong>NUnit Test Project<\/strong> from the list of templates.<\/li>\n\n\n\n<li>Name it (e.g., <code>MyApp.Tests.Unit<\/code>).<\/li>\n\n\n\n<li>Add references to the main project that you want to test (<code>MyApp<\/code>).<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>How to See Test Results?<\/strong><\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">There are different ways to run tests and view the results in Visual Studio and with command-line tools.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><strong>Using Test Explorer in Visual Studio<\/strong><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Visual Studio provides a <strong>Test Explorer<\/strong> window where you can see all the test results.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Steps to View Test Results in Test Explorer<\/strong>:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Open Test Explorer<\/strong>:\n<ul class=\"wp-block-list\">\n<li>Go to <strong>Test<\/strong> > <strong>Test Explorer<\/strong> in the top menu, or press <code>Ctrl + E, T<\/code>.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Run Tests<\/strong>:\n<ul class=\"wp-block-list\">\n<li>You can run all tests by clicking on <strong>Run All<\/strong>, or run specific tests by selecting them.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>View Results<\/strong>:\n<ul class=\"wp-block-list\">\n<li>The Test Explorer will display the results\u2014<strong>passed<\/strong>, <strong>failed<\/strong>, <strong>skipped<\/strong>, etc.<\/li>\n\n\n\n<li>If a test fails, you can click on it to see the <strong>error message<\/strong> and <strong>stack trace<\/strong>.<\/li>\n<\/ul>\n<\/li>\n<\/ol>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Sample Test Files<\/strong><\/h2>\n\n\n\n<h4 class=\"wp-block-heading\"><strong>1. ProductControllerTests.cs (Unit Test for the Controller)<\/strong><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">In this file, we have unit tests for the <code>ProductController<\/code> class. Typically, we mock the dependencies (in this case, the <code>IProductService<\/code>) to isolate the tests.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\nusing Xunit;\nusing Moq;\nusing Microsoft.AspNetCore.Mvc;\nusing MyApp.Controllers;\nusing MyApp.Services;\n\npublic class ProductControllerTests\n{\n    &#x5B;Fact]\n    public void GetProductById_ShouldReturnOk_WhenProductExists()\n    {\n        \/\/ Arrange\n        var mockService = new Mock&lt;IProductService&gt;();\n        mockService.Setup(service =&gt; service.GetProductById(1))\n                   .Returns(new Product { Id = 1, Name = &quot;Laptop&quot;, Price = 1000 });\n\n        var controller = new ProductController(mockService.Object);\n\n        \/\/ Act\n        var result = controller.GetProduct(1) as OkObjectResult;\n\n        \/\/ Assert\n        Assert.NotNull(result);\n        Assert.Equal(200, result.StatusCode);\n    }\n\n    &#x5B;Fact]\n    public void GetProductById_ShouldReturnNotFound_WhenProductDoesNotExist()\n    {\n        \/\/ Arrange\n        var mockService = new Mock&lt;IProductService&gt;();\n        mockService.Setup(service =&gt; service.GetProductById(999)).Returns((Product)null);\n\n        var controller = new ProductController(mockService.Object);\n\n        \/\/ Act\n        var result = controller.GetProduct(999);\n\n        \/\/ Assert\n        Assert.IsType&lt;NotFoundResult&gt;(result);\n    }\n}\n<\/pre><\/div>\n\n\n<h4 class=\"wp-block-heading\"><strong>2. ProductServiceTests.cs (Unit Test for the Service)<\/strong><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">This file contains tests for the <code>ProductService<\/code>. We use a mocked repository to ensure that only the business logic of the service is being tested.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\nusing Xunit;\nusing Moq;\nusing MyApp.Repositories;\nusing MyApp.Services;\nusing MyApp.Models;\n\npublic class ProductServiceTests\n{\n    &#x5B;Fact]\n    public void GetProductById_ShouldReturnProduct_WhenProductExists()\n    {\n        \/\/ Arrange\n        var mockRepo = new Mock&lt;IProductRepository&gt;();\n        mockRepo.Setup(repo =&gt; repo.GetProductById(1))\n                .Returns(new Product { Id = 1, Name = &quot;Laptop&quot;, Price = 1000 });\n\n        var productService = new ProductService(mockRepo.Object);\n\n        \/\/ Act\n        var product = productService.GetProductById(1);\n\n        \/\/ Assert\n        Assert.NotNull(product);\n        Assert.Equal(1, product.Id);\n        Assert.Equal(&quot;Laptop&quot;, product.Name);\n    }\n\n    &#x5B;Fact]\n    public void AddProduct_ShouldCallAddMethodOnce()\n    {\n        \/\/ Arrange\n        var mockRepo = new Mock&lt;IProductRepository&gt;();\n        var productService = new ProductService(mockRepo.Object);\n        var product = new Product { Id = 1, Name = &quot;Tablet&quot;, Price = 500.0m };\n\n        \/\/ Act\n        productService.AddProduct(product);\n\n        \/\/ Assert\n        mockRepo.Verify(repo =&gt; repo.AddProduct(product), Times.Once);\n    }\n}\n<\/pre><\/div>\n\n\n<h4 class=\"wp-block-heading\"><strong>3. ProductRepositoryTests.cs (Unit Test for the Repository)<\/strong><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">This file contains tests for the <code>ProductRepository<\/code>. Typically, repository tests might interact with an in-memory database or a lightweight database for testing.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\nusing Xunit;\nusing System;\nusing System.Data.SqlClient;\nusing MyApp.Repositories;\nusing MyApp.Models;\n\npublic class ProductRepositoryTests\n{\n    &#x5B;Fact]\n    public void AddProduct_ShouldThrowException_WhenDatabaseUnavailable()\n    {\n        \/\/ Arrange\n        string invalidConnectionString = &quot;InvalidConnectionString&quot;;\n        var repository = new ProductRepository(invalidConnectionString);\n        var product = new Product { Name = &quot;Phone&quot;, Price = 300.0m };\n\n        \/\/ Act &amp; Assert\n        Assert.Throws&lt;Exception&gt;(() =&gt; repository.AddProduct(product));\n    }\n}\n<\/pre><\/div>\n\n\n<ul class=\"wp-block-list\">\n<li>In this test, an invalid connection string is provided to simulate a database connection issue, and the test expects an <strong>exception<\/strong> to be thrown.<\/li>\n<\/ul>\n\n\n\n<h4 class=\"wp-block-heading\"><strong>4. ProductApiIntegrationTests.cs (Integration Test for the API Endpoint)<\/strong><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">This file contains an integration test that simulates a request to the API to validate end-to-end behavior.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\nusing System.Net.Http;\nusing System.Text;\nusing System.Text.Json;\nusing System.Threading.Tasks;\nusing Microsoft.AspNetCore.Mvc.Testing;\nusing Xunit;\n\npublic class ProductApiIntegrationTests : IClassFixture&lt;WebApplicationFactory&lt;Program&gt;&gt;\n{\n    private readonly HttpClient _client;\n\n    public ProductApiIntegrationTests(WebApplicationFactory&lt;Program&gt; factory)\n    {\n        _client = factory.CreateClient();\n    }\n\n    &#x5B;Fact]\n    public async Task CreateProduct_ShouldReturnCreated_WhenProductIsValid()\n    {\n        \/\/ Arrange\n        var product = new { Name = &quot;Smartphone&quot;, Price = 800 };\n        var content = new StringContent(JsonSerializer.Serialize(product), Encoding.UTF8, &quot;application\/json&quot;);\n\n        \/\/ Act\n        var response = await _client.PostAsync(&quot;\/api\/products&quot;, content);\n\n        \/\/ Assert\n        Assert.Equal(System.Net.HttpStatusCode.Created, response.StatusCode);\n    }\n}\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\"><strong>Storing Each Test in a Separate File<\/strong><\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Separation of Concerns<\/strong>: Each test class has a <strong>single responsibility<\/strong>\u2014testing only the behavior of the respective class it is named after.<\/li>\n\n\n\n<li><strong>Readability<\/strong>: When each test class is in a separate file, it is easier to navigate the codebase, find specific tests, and maintain them.<\/li>\n\n\n\n<li><strong>Scaling the Project<\/strong>: As the project grows, storing each test in a separate file helps to <strong>organize<\/strong> and <strong>scale<\/strong> the test suite without mixing test cases together, leading to more maintainable code.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Examples<\/strong><\/h2>\n\n\n\n<h4 class=\"wp-block-heading\"><strong>Simple Example: Unit Test for Controller Action<\/strong><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Test the <code>GetProductById<\/code> controller action for a valid product ID.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Code Snippet<\/strong>:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\n&#x5B;Fact]\npublic void GetProductById_ShouldReturnOk_WhenProductExists()\n{\n    var mockService = new Mock&lt;IProductService&gt;();\n    mockService.Setup(service =&gt; service.GetProductById(1))\n               .Returns(new Product { Id = 1, Name = &quot;Laptop&quot;, Price = 1000 });\n\n    var controller = new ProductController(mockService.Object);\n    var result = controller.GetProduct(1) as OkObjectResult;\n\n    Assert.NotNull(result);\n    Assert.Equal(200, result.StatusCode);\n}\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\"><strong>Real-Life Example<\/strong>: In an <strong>e-commerce<\/strong> system, ensure that the API returns <code>200 OK<\/code> for valid product requests.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><strong>Simple Example: Mock Repository for AddProduct<\/strong><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Use <strong>Moq<\/strong> to verify that a repository's <code>AddProduct<\/code> method is called.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Code Snippet<\/strong>:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\n&#x5B;Fact]\npublic void AddProduct_ShouldCallRepository()\n{\n    var mockRepo = new Mock&lt;IProductRepository&gt;();\n    var productService = new ProductService(mockRepo.Object);\n    var product = new Product { Name = &quot;Tablet&quot;, Price = 300 };\n\n    productService.AddProduct(product);\n\n    mockRepo.Verify(repo =&gt; repo.AddProduct(product), Times.Once);\n}\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\"><strong>Real-Life Example<\/strong>: In a <strong>financial system<\/strong>, verify that adding a new transaction is processed correctly.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><strong>Simple Example: Integration Test for Creating Product<\/strong><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Write an integration test to add a product through the API.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Code Snippet<\/strong>:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\n&#x5B;Fact]\npublic async Task CreateProduct_ShouldReturnCreated_WhenValidProduct()\n{\n    var product = new { Name = &quot;Smartphone&quot;, Price = 800 };\n    var content = new StringContent(JsonSerializer.Serialize(product), Encoding.UTF8, &quot;application\/json&quot;);\n\n    var response = await _client.PostAsync(&quot;\/api\/products&quot;, content);\n\n    Assert.Equal(System.Net.HttpStatusCode.Created, response.StatusCode);\n}\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\"><strong>Real-Life Example<\/strong>: In an <strong>inventory system<\/strong>, validate that new products are created correctly via API endpoints.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Key Takeaways<\/strong><\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Unit Testing<\/strong>: Test small, isolated units of code, such as service methods, to ensure correctness.<\/li>\n\n\n\n<li><strong>Mocking<\/strong>: Use <strong>Moq<\/strong> to create mocks of dependencies, allowing for isolated and reliable testing.<\/li>\n\n\n\n<li><strong>Integration Testing<\/strong>: Ensure that components work together by testing complete flows, including databases, services, and APIs.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Practical Questions<\/strong><\/h3>\n\n\n\n<ol class=\"wp-block-list\">\n<li>What are the main differences between <strong>unit testing<\/strong> and <strong>integration testing<\/strong>, and why are both important?<\/li>\n\n\n\n<li>How can you use <strong>Moq<\/strong> to verify that a service method correctly calls its dependencies?<\/li>\n\n\n\n<li>How would you write an <strong>integration test<\/strong> to ensure that the entire API works as expected?<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>New Concepts in .NET 8<\/strong><\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>New in .NET 8<\/strong>:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Test Improvements<\/strong>: .NET 8 introduces enhanced tools for integration testing, allowing for easier setup and execution, especially when working with <strong>minimal APIs<\/strong>. Integration with <strong>Native AOT<\/strong> improves testing for applications that aim to be lightweight and optimized.<\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>Learning Objectives Unit Testing What is Unit Testing? Unit testing is the process of testing small, isolated pieces of code (units), such as methods in a class, to ensure they work as expected. The primary goal of unit testing is to verify that individual units of code function correctly in isolation. In ASP.NET Core, unit [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"ocean_post_layout":"","ocean_both_sidebars_style":"","ocean_both_sidebars_content_width":0,"ocean_both_sidebars_sidebars_width":0,"ocean_sidebar":"","ocean_second_sidebar":"","ocean_disable_margins":"enable","ocean_add_body_class":"","ocean_shortcode_before_top_bar":"","ocean_shortcode_after_top_bar":"","ocean_shortcode_before_header":"","ocean_shortcode_after_header":"","ocean_has_shortcode":"","ocean_shortcode_after_title":"","ocean_shortcode_before_footer_widgets":"","ocean_shortcode_after_footer_widgets":"","ocean_shortcode_before_footer_bottom":"","ocean_shortcode_after_footer_bottom":"","ocean_display_top_bar":"default","ocean_display_header":"default","ocean_header_style":"","ocean_center_header_left_menu":"","ocean_custom_header_template":"","ocean_custom_logo":0,"ocean_custom_retina_logo":0,"ocean_custom_logo_max_width":0,"ocean_custom_logo_tablet_max_width":0,"ocean_custom_logo_mobile_max_width":0,"ocean_custom_logo_max_height":0,"ocean_custom_logo_tablet_max_height":0,"ocean_custom_logo_mobile_max_height":0,"ocean_header_custom_menu":"","ocean_menu_typo_font_family":"","ocean_menu_typo_font_subset":"","ocean_menu_typo_font_size":0,"ocean_menu_typo_font_size_tablet":0,"ocean_menu_typo_font_size_mobile":0,"ocean_menu_typo_font_size_unit":"px","ocean_menu_typo_font_weight":"","ocean_menu_typo_font_weight_tablet":"","ocean_menu_typo_font_weight_mobile":"","ocean_menu_typo_transform":"","ocean_menu_typo_transform_tablet":"","ocean_menu_typo_transform_mobile":"","ocean_menu_typo_line_height":0,"ocean_menu_typo_line_height_tablet":0,"ocean_menu_typo_line_height_mobile":0,"ocean_menu_typo_line_height_unit":"","ocean_menu_typo_spacing":0,"ocean_menu_typo_spacing_tablet":0,"ocean_menu_typo_spacing_mobile":0,"ocean_menu_typo_spacing_unit":"","ocean_menu_link_color":"","ocean_menu_link_color_hover":"","ocean_menu_link_color_active":"","ocean_menu_link_background":"","ocean_menu_link_hover_background":"","ocean_menu_link_active_background":"","ocean_menu_social_links_bg":"","ocean_menu_social_hover_links_bg":"","ocean_menu_social_links_color":"","ocean_menu_social_hover_links_color":"","ocean_disable_title":"default","ocean_disable_heading":"default","ocean_post_title":"","ocean_post_subheading":"","ocean_post_title_style":"","ocean_post_title_background_color":"","ocean_post_title_background":0,"ocean_post_title_bg_image_position":"","ocean_post_title_bg_image_attachment":"","ocean_post_title_bg_image_repeat":"","ocean_post_title_bg_image_size":"","ocean_post_title_height":0,"ocean_post_title_bg_overlay":0.5,"ocean_post_title_bg_overlay_color":"","ocean_disable_breadcrumbs":"default","ocean_breadcrumbs_color":"","ocean_breadcrumbs_separator_color":"","ocean_breadcrumbs_links_color":"","ocean_breadcrumbs_links_hover_color":"","ocean_display_footer_widgets":"default","ocean_display_footer_bottom":"default","ocean_custom_footer_template":"","_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"ocean_post_oembed":"","ocean_post_self_hosted_media":"","ocean_post_video_embed":"","ocean_link_format":"","ocean_link_format_target":"self","ocean_quote_format":"","ocean_quote_format_link":"post","ocean_gallery_link_images":"on","ocean_gallery_id":[],"footnotes":""},"categories":[79],"tags":[],"class_list":["post-1989","post","type-post","status-publish","format-standard","hentry","category-dotnet-8","entry"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.9 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Testing - Code Notebook<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/epicmarketing.co.il\/notebook\/testing\/\" \/>\n<meta property=\"og:locale\" content=\"he_IL\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Testing - Code Notebook\" \/>\n<meta property=\"og:description\" content=\"Learning Objectives Unit Testing What is Unit Testing? Unit testing is the process of testing small, isolated pieces of code (units), such as methods in a class, to ensure they work as expected. The primary goal of unit testing is to verify that individual units of code function correctly in isolation. In ASP.NET Core, unit [&hellip;]\" \/>\n<meta property=\"og:url\" content=\"https:\/\/epicmarketing.co.il\/notebook\/testing\/\" \/>\n<meta property=\"og:site_name\" content=\"Code Notebook\" \/>\n<meta property=\"article:published_time\" content=\"2024-11-01T06:54:39+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2024-11-01T07:16:37+00:00\" \/>\n<meta name=\"author\" content=\"kerendanino\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"\u05e0\u05db\u05ea\u05d1 \u05e2\u05dc \u05d9\u05d3\" \/>\n\t<meta name=\"twitter:data1\" content=\"kerendanino\" \/>\n\t<meta name=\"twitter:label2\" content=\"\u05d6\u05de\u05df \u05e7\u05e8\u05d9\u05d0\u05d4 \u05de\u05d5\u05e2\u05e8\u05da\" \/>\n\t<meta name=\"twitter:data2\" content=\"7 \u05d3\u05e7\u05d5\u05ea\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\\\/\\\/epicmarketing.co.il\\\/notebook\\\/testing\\\/#article\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/epicmarketing.co.il\\\/notebook\\\/testing\\\/\"},\"author\":{\"name\":\"kerendanino\",\"@id\":\"https:\\\/\\\/epicmarketing.co.il\\\/notebook\\\/#\\\/schema\\\/person\\\/195dfc625818eadda7903d456890e24c\"},\"headline\":\"Testing\",\"datePublished\":\"2024-11-01T06:54:39+00:00\",\"dateModified\":\"2024-11-01T07:16:37+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\\\/\\\/epicmarketing.co.il\\\/notebook\\\/testing\\\/\"},\"wordCount\":1277,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\\\/\\\/epicmarketing.co.il\\\/notebook\\\/#organization\"},\"articleSection\":[\"Dotnet 8\"],\"inLanguage\":\"he-IL\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\\\/\\\/epicmarketing.co.il\\\/notebook\\\/testing\\\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/epicmarketing.co.il\\\/notebook\\\/testing\\\/\",\"url\":\"https:\\\/\\\/epicmarketing.co.il\\\/notebook\\\/testing\\\/\",\"name\":\"Testing - Code Notebook\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/epicmarketing.co.il\\\/notebook\\\/#website\"},\"datePublished\":\"2024-11-01T06:54:39+00:00\",\"dateModified\":\"2024-11-01T07:16:37+00:00\",\"breadcrumb\":{\"@id\":\"https:\\\/\\\/epicmarketing.co.il\\\/notebook\\\/testing\\\/#breadcrumb\"},\"inLanguage\":\"he-IL\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/epicmarketing.co.il\\\/notebook\\\/testing\\\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/epicmarketing.co.il\\\/notebook\\\/testing\\\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/epicmarketing.co.il\\\/notebook\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Testing\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/epicmarketing.co.il\\\/notebook\\\/#website\",\"url\":\"https:\\\/\\\/epicmarketing.co.il\\\/notebook\\\/\",\"name\":\"Code Notebook\",\"description\":\"Easy coding\",\"publisher\":{\"@id\":\"https:\\\/\\\/epicmarketing.co.il\\\/notebook\\\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/epicmarketing.co.il\\\/notebook\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"he-IL\"},{\"@type\":\"Organization\",\"@id\":\"https:\\\/\\\/epicmarketing.co.il\\\/notebook\\\/#organization\",\"name\":\"Code Notebook\",\"url\":\"https:\\\/\\\/epicmarketing.co.il\\\/notebook\\\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"he-IL\",\"@id\":\"https:\\\/\\\/epicmarketing.co.il\\\/notebook\\\/#\\\/schema\\\/logo\\\/image\\\/\",\"url\":\"https:\\\/\\\/epicmarketing.co.il\\\/notebook\\\/wp-content\\\/uploads\\\/2023\\\/07\\\/logo-epic-marketing-05.png\",\"contentUrl\":\"https:\\\/\\\/epicmarketing.co.il\\\/notebook\\\/wp-content\\\/uploads\\\/2023\\\/07\\\/logo-epic-marketing-05.png\",\"width\":3626,\"height\":1942,\"caption\":\"Code Notebook\"},\"image\":{\"@id\":\"https:\\\/\\\/epicmarketing.co.il\\\/notebook\\\/#\\\/schema\\\/logo\\\/image\\\/\"}},{\"@type\":\"Person\",\"@id\":\"https:\\\/\\\/epicmarketing.co.il\\\/notebook\\\/#\\\/schema\\\/person\\\/195dfc625818eadda7903d456890e24c\",\"name\":\"kerendanino\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"he-IL\",\"@id\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/285cc9389c66aa46da1e26a474b1e90e9efaf3fa21f1b928cbd63ce5f0e89c63?s=96&d=mm&r=g\",\"url\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/285cc9389c66aa46da1e26a474b1e90e9efaf3fa21f1b928cbd63ce5f0e89c63?s=96&d=mm&r=g\",\"contentUrl\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/285cc9389c66aa46da1e26a474b1e90e9efaf3fa21f1b928cbd63ce5f0e89c63?s=96&d=mm&r=g\",\"caption\":\"kerendanino\"},\"url\":\"https:\\\/\\\/epicmarketing.co.il\\\/notebook\\\/author\\\/kerendanino\\\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Testing - Code Notebook","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:\/\/epicmarketing.co.il\/notebook\/testing\/","og_locale":"he_IL","og_type":"article","og_title":"Testing - Code Notebook","og_description":"Learning Objectives Unit Testing What is Unit Testing? Unit testing is the process of testing small, isolated pieces of code (units), such as methods in a class, to ensure they work as expected. The primary goal of unit testing is to verify that individual units of code function correctly in isolation. In ASP.NET Core, unit [&hellip;]","og_url":"https:\/\/epicmarketing.co.il\/notebook\/testing\/","og_site_name":"Code Notebook","article_published_time":"2024-11-01T06:54:39+00:00","article_modified_time":"2024-11-01T07:16:37+00:00","author":"kerendanino","twitter_card":"summary_large_image","twitter_misc":{"\u05e0\u05db\u05ea\u05d1 \u05e2\u05dc \u05d9\u05d3":"kerendanino","\u05d6\u05de\u05df \u05e7\u05e8\u05d9\u05d0\u05d4 \u05de\u05d5\u05e2\u05e8\u05da":"7 \u05d3\u05e7\u05d5\u05ea"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/epicmarketing.co.il\/notebook\/testing\/#article","isPartOf":{"@id":"https:\/\/epicmarketing.co.il\/notebook\/testing\/"},"author":{"name":"kerendanino","@id":"https:\/\/epicmarketing.co.il\/notebook\/#\/schema\/person\/195dfc625818eadda7903d456890e24c"},"headline":"Testing","datePublished":"2024-11-01T06:54:39+00:00","dateModified":"2024-11-01T07:16:37+00:00","mainEntityOfPage":{"@id":"https:\/\/epicmarketing.co.il\/notebook\/testing\/"},"wordCount":1277,"commentCount":0,"publisher":{"@id":"https:\/\/epicmarketing.co.il\/notebook\/#organization"},"articleSection":["Dotnet 8"],"inLanguage":"he-IL","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/epicmarketing.co.il\/notebook\/testing\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/epicmarketing.co.il\/notebook\/testing\/","url":"https:\/\/epicmarketing.co.il\/notebook\/testing\/","name":"Testing - Code Notebook","isPartOf":{"@id":"https:\/\/epicmarketing.co.il\/notebook\/#website"},"datePublished":"2024-11-01T06:54:39+00:00","dateModified":"2024-11-01T07:16:37+00:00","breadcrumb":{"@id":"https:\/\/epicmarketing.co.il\/notebook\/testing\/#breadcrumb"},"inLanguage":"he-IL","potentialAction":[{"@type":"ReadAction","target":["https:\/\/epicmarketing.co.il\/notebook\/testing\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/epicmarketing.co.il\/notebook\/testing\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/epicmarketing.co.il\/notebook\/"},{"@type":"ListItem","position":2,"name":"Testing"}]},{"@type":"WebSite","@id":"https:\/\/epicmarketing.co.il\/notebook\/#website","url":"https:\/\/epicmarketing.co.il\/notebook\/","name":"Code Notebook","description":"Easy coding","publisher":{"@id":"https:\/\/epicmarketing.co.il\/notebook\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/epicmarketing.co.il\/notebook\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"he-IL"},{"@type":"Organization","@id":"https:\/\/epicmarketing.co.il\/notebook\/#organization","name":"Code Notebook","url":"https:\/\/epicmarketing.co.il\/notebook\/","logo":{"@type":"ImageObject","inLanguage":"he-IL","@id":"https:\/\/epicmarketing.co.il\/notebook\/#\/schema\/logo\/image\/","url":"https:\/\/epicmarketing.co.il\/notebook\/wp-content\/uploads\/2023\/07\/logo-epic-marketing-05.png","contentUrl":"https:\/\/epicmarketing.co.il\/notebook\/wp-content\/uploads\/2023\/07\/logo-epic-marketing-05.png","width":3626,"height":1942,"caption":"Code Notebook"},"image":{"@id":"https:\/\/epicmarketing.co.il\/notebook\/#\/schema\/logo\/image\/"}},{"@type":"Person","@id":"https:\/\/epicmarketing.co.il\/notebook\/#\/schema\/person\/195dfc625818eadda7903d456890e24c","name":"kerendanino","image":{"@type":"ImageObject","inLanguage":"he-IL","@id":"https:\/\/secure.gravatar.com\/avatar\/285cc9389c66aa46da1e26a474b1e90e9efaf3fa21f1b928cbd63ce5f0e89c63?s=96&d=mm&r=g","url":"https:\/\/secure.gravatar.com\/avatar\/285cc9389c66aa46da1e26a474b1e90e9efaf3fa21f1b928cbd63ce5f0e89c63?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/285cc9389c66aa46da1e26a474b1e90e9efaf3fa21f1b928cbd63ce5f0e89c63?s=96&d=mm&r=g","caption":"kerendanino"},"url":"https:\/\/epicmarketing.co.il\/notebook\/author\/kerendanino\/"}]}},"jetpack_featured_media_url":"","jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/epicmarketing.co.il\/notebook\/wp-json\/wp\/v2\/posts\/1989","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/epicmarketing.co.il\/notebook\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/epicmarketing.co.il\/notebook\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/epicmarketing.co.il\/notebook\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/epicmarketing.co.il\/notebook\/wp-json\/wp\/v2\/comments?post=1989"}],"version-history":[{"count":5,"href":"https:\/\/epicmarketing.co.il\/notebook\/wp-json\/wp\/v2\/posts\/1989\/revisions"}],"predecessor-version":[{"id":1997,"href":"https:\/\/epicmarketing.co.il\/notebook\/wp-json\/wp\/v2\/posts\/1989\/revisions\/1997"}],"wp:attachment":[{"href":"https:\/\/epicmarketing.co.il\/notebook\/wp-json\/wp\/v2\/media?parent=1989"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/epicmarketing.co.il\/notebook\/wp-json\/wp\/v2\/categories?post=1989"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/epicmarketing.co.il\/notebook\/wp-json\/wp\/v2\/tags?post=1989"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}