C# NUnit Unit Test Example

Date: 2019-11-14
using NSubstitute;
using NUnit.Framework;
using Plugin.Domain.Edi;
using Plugin.Domain.Messages;
using Plugin.Domain.Repositories;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Plugin.Tests.Domain
{
    [TestFixture]
    public class EdiOrderServiceTests
    {
        private readonly CommonEdiProvider _provider1 = new CommonEdiProvider(TypeEdiProvider.TransusXml, "https://webconnect.transus.com/Exchange.asmx", "User 1");
        private readonly CommonEdiProvider _provider2 = new CommonEdiProvider(TypeEdiProvider.TransusXml, "https://webconnect.transus.com/Exchange.asmx", "User 2");
        private readonly OrderMessage _orderMessage1 = new OrderMessage() { MessageReference = "1" };
        private readonly OrderMessage _orderMessage2 = new OrderMessage() { MessageReference = "2" };
        private readonly OrderMessage _orderMessage3 = new OrderMessage() { MessageReference = "3" };

        private IEdiProviderRepository _ediProviderRepository;
        private IOrderMessageRepository _orderMessageRepository;
        private IEdiOrderRepository _ediOrderRepository;

        [SetUp]
        public void SetUpTests()
        {
            _ediProviderRepository = Substitute.For<IEdiProviderRepository>();
            _orderMessageRepository = Substitute.For<IOrderMessageRepository>();
            _ediOrderRepository = Substitute.For<IEdiOrderRepository>();

            _ediProviderRepository.GetEdiProvidersByType(TypeEdiProvider.TransusXml).Returns(new List<CommonEdiProvider> { _provider1, _provider2 });

            _orderMessageRepository.GetOrderMessages(_provider1).Returns(new List<OrderMessage> { _orderMessage1, _orderMessage2 });
            _orderMessageRepository.GetOrderMessages(_provider2).Returns(new List<OrderMessage> { _orderMessage3 });
        }

        [Test]
        public async Task GetTransusEdiOrdersFromProvidersTest()
        {
            // arrange
            var ediOrderService = new EdiOrderService(_ediProviderRepository, _orderMessageRepository, _ediOrderRepository);

            // act
            await ediOrderService.GetTransusEdiOrdersFromProviders();

            // assert
            await _ediProviderRepository.Received().GetEdiProvidersByType(TypeEdiProvider.TransusXml);
            await _orderMessageRepository.Received().GetOrderMessages(_provider1);
            await _orderMessageRepository.Received().GetOrderMessages(_provider2);
            var arg = Arg.Is<List<OrderMessage>>(l => l[0] == _orderMessage1 && l[1] == _orderMessage2 && l[2] == _orderMessage3);
            await _ediOrderRepository.Received().CreateAndSaveEdiOrdersFromOrderMessages(arg);
        }
    }
}
28750cookie-checkC# NUnit Unit Test Example