devfunkd
devfunkd

Reputation: 3234

Moq setting up variables inside a method

I have the following method that I am trying to test, but my variables are null even if I try to set them up.

        public void Cancel(Guid id)
        {
            var order = _orderRepository.Find(o => o.Id == id); ** This never gets set, even with the setup below.**
            if (order == null) return;  ** Test Fails here. Returns and all assertions fails.**

            order.Status = OrderStatus.Cancelled;
            _orderRepository.Update(order);
        }

        [SetUp]
        public void Setup()
        {
            _orderRepositoryMock = new Mock<IRepository<Order>>();
            _accountServiceMock = new Mock<IAccountService>();

            _orderService = new OrderService(_accountServiceMock.Object, _orderRepositoryMock.Object);

            order = new Order()
            {
                Id = Guid.NewGuid(),
                Customer= new ApplicationUser()
                {
                    Id = Guid.NewGuid().ToString(),
                    Email = "[email protected]",
                    FirstName = "Tester",
                    LastName = "Test",
                    Address = "123 45 Ave",
                    City = "ABCVille",
                    PhoneNumber = "1-888-888-8888",
                    PostalCode = "T3J 0A4",
                    Province = "Super"
                },
                OrderAddons = new List<OrderAddon>(),
                Total = 363.99m,
                Status = OrderStatus.Created
            };
        }

    [Test]
    public void CancelShouldCallRepositoryWhenValid()
    {
        //var order ... (test data, in setUp)
        var id = Guid.NewGuid();
        order.Id = id;

        // Repository Setup
        _orderRepositoryMock.Setup(x => x.Find(o => o.Id == id)).Returns(order);

        var wasOrderStatusUpdatedCorrectly = false;
        _orderRepositoryMock.Setup(x => x.Update(order))
            .Callback((Order o) =>
            {
                wasOrderStatusUpdatedCorrectly = o.Status == OrderStatus.Cancelled;
            });

        // Test Service
        _orderService.Cancel(id);

        // Test Assertions
        _orderRepositoryMock.Verify(x => x.Find(o => o.Id == It.IsAny<Guid>()), Times.Once);
        _orderRepositoryMock.Verify(x => x.Update(order), Times.Once);
    }

Is there anyway to test "var order" ? I tried SetupGet as well and didn't seem to work, Moq is new to me so forgive me in advance if this is something simple and easy.

Upvotes: 1

Views: 5267

Answers (1)

Andrew Whitaker
Andrew Whitaker

Reputation: 126042

I think the problem is the Expression that the repository's Find method expects. Try this instead:

_orderRepositoryMock
    .Setup(x => x.Find(It.IsAny<Expression<Func<Order, bool>>>()))
    .Returns(order);

I'm just guessing at the type parameter for the Expression<>, but hopefully that helps.

Upvotes: 1

Related Questions