Skip to content

[FEATURE] Add Integration Tests project with WireMock fixture #127

Description

@guibranco

Description

We need to add comprehensive integration tests for our C# integration library that interacts with an HTTP ERP (Sankhya) service. These tests should ensure that our integration library correctly handles various scenarios when communicating with the ERP service.

Problem Statement

  • Current Issue: The current integration testing coverage for the HTTP ERP service is insufficient. We need to verify that the integration library works correctly with the ERP service and handles different scenarios, including error cases and edge cases.
  • Impact: Without proper integration tests, there is a risk of undetected issues in how our library interacts with the ERP service, potentially leading to bugs and unreliable behavior in production.

Proposed Solution

  • Develop Integration Tests:
    • Use XUnit for testing.
    • Employ WireMock to simulate HTTP responses from the ERP service.
    • Use Snapshooter for snapshot testing to compare actual responses against expected results.
    • Utilize NSubstitute for mocking dependencies where necessary.
    • Use Bogus to generate realistic fake data for testing.

Implementation Steps

  1. Set Up Integration Tests:

    • Create a new test project if one does not already exist for integration tests.
    • Add dependencies for XUnit, WireMock, Snapshooter, NSubstitute, and Bogus.
    <ItemGroup>
      <PackageReference Include="xunit" Version="2.4.1" />
      <PackageReference Include="WireMock.Net" Version="3.1.0" />
      <PackageReference Include="Snapshooter" Version="1.0.0" />
      <PackageReference Include="NSubstitute" Version="4.2.2" />
      <PackageReference Include="Bogus" Version="33.1.0" />
    </ItemGroup>
  2. Configure WireMock for Fake HTTP Requests:

    • Set up WireMock to simulate various HTTP responses from the ERP service. This will allow us to test how the integration library handles different scenarios.
    public class ErpServiceTests : IClassFixture<WireMockServerFixture>
    {
        private readonly WireMockServerFixture _fixture;
    
        public ErpServiceTests(WireMockServerFixture fixture)
        {
            _fixture = fixture;
        }
    
        [Fact]
        public async Task ShouldHandleSuccessfulResponse()
        {
            // Arrange
            _fixture.Server
                .Given(Request.Create().WithPath("/api/orders").UsingGet())
                .RespondWith(Response.Create().WithStatusCode(200).WithBody("{ \"orderId\": \"12345\" }"));
    
            // Act
            var result = await _service.GetOrderAsync("12345");
    
            // Assert
            Assert.Equal("12345", result.OrderId);
        }
    }
  3. Use Snapshooter for Response Comparison:

    • Implement Snapshooter to take snapshots of responses and compare them with expected results. This will help ensure consistency in the responses.
    [Fact]
    public async Task ShouldMatchExpectedResponse()
    {
        // Arrange
        var expectedResponse = new { OrderId = "12345" };
    
        // Act
        var actualResponse = await _service.GetOrderAsync("12345");
    
        // Assert
        actualResponse.Should().MatchSnapshot();
    }
  4. Generate Fake Data with Bogus:

    • Use Bogus to create realistic fake data for various tests, such as generating order details, customer information, etc.
    public class OrderGenerator
    {
        public static Order CreateFakeOrder()
        {
            var faker = new Faker<Order>()
                .RuleFor(o => o.OrderId, f => f.Random.Guid().ToString())
                .RuleFor(o => o.CustomerName, f => f.Name.FullName())
                .RuleFor(o => o.Amount, f => f.Finance.Amount());
    
            return faker.Generate();
        }
    }
  5. Mock Dependencies with NSubstitute:

    • Use NSubstitute to mock any dependencies that are not directly related to the ERP service interactions but are necessary for testing.
    public class OrderServiceTests
    {
        private readonly IOrderRepository _orderRepository;
        private readonly OrderService _orderService;
    
        public OrderServiceTests()
        {
            _orderRepository = Substitute.For<IOrderRepository>();
            _orderService = new OrderService(_orderRepository);
        }
    
        [Fact]
        public async Task ShouldReturnOrder()
        {
            // Arrange
            var fakeOrder = OrderGenerator.CreateFakeOrder();
            _orderRepository.GetOrderAsync(Arg.Any<string>()).Returns(Task.FromResult(fakeOrder));
    
            // Act
            var result = await _orderService.GetOrderAsync(fakeOrder.OrderId);
    
            // Assert
            Assert.Equal(fakeOrder.OrderId, result.OrderId);
        }
    }
  6. Run and Validate Tests:

    • Execute all integration tests to ensure that they cover the necessary scenarios and pass successfully.
    • Review and refine tests based on results and feedback.

Additional Notes

  • Ensure that the integration tests are comprehensive and cover a wide range of scenarios, including success and failure cases.
  • Collaborate with the development team to identify any additional test cases or scenarios that should be included.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    .NETPull requests that update .net codedependenciesPull requests that update a dependency fileenhancementNew feature or requestgitautoGitAuto label to trigger the app in a issue.resiliencetestsTests⚙️ CI/CDContinuous Integration/Continuous Deployment processes📝 documentationTasks related to writing or updating documentation🚨 securitySecurity-related issues or improvements

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions