0

我正在使用 Moq.Contrib 的 AutoMockContainer ( https://code.google.com/p/moq-contrib/wiki/Automocking ) 创建具体类型的实例并自动满足其依赖关系。问题是我想在 AutoMockContanier.Create 返回的 T 上创建一个设置。我需要 Mock,但 Create 返回 T?下面的示例代码(也在这里https://dotnetfiddle.net/Sa1jCq) -

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
using Moq;

namespace AutoMoqTest
{
    public interface ICustomerValidator
    {
        bool IsAdult(int age);
    }

    public class CustomerValidator:ICustomerValidator
    {

        public bool IsAdult(int age)
        {
            return age >= 18;
        }
    }

    public class Customer
    {
        private ICustomerValidator CustomerValidator { get; set; }
        public Customer(ICustomerValidator customerValidator)
        {
            CustomerValidator = customerValidator;
        }

        public int CustomerAge { get { return 10; } }

        public bool IsCustomerAdult()
        {
            return CustomerValidator.IsAdult(CustomerAge);
        }
    }

    [TestFixture]
    public class DITest
    {
        [Test]
        public void IsAdult_should_be_true_for_customer_having_age_20()
        {
            var factory = new MockRepository(MockBehavior.Loose);
            var container = new AutoMockContainer(factory);
            //var customer = container.Create<Customer>();
            var customerMock = container.GetMock<Customer>();
            customerMock.Setup(x=>x.CustomerAge).Returns(20); //NEED TO ACHIEVE THIS SETUP
           // Assert.IsTrue(customer.IsCustomerAdult());
        }
    }
}
4

1 回答 1

0

看来你把事情弄复杂了。你真的不需要自动模拟。如果您想从单元测试中获得最大的收益,请保持简单,重要的是隔离测试。只需为 CustomerValidator 编写一个测试

[TestFixture]
public class CustomerValidatorTest
{

    [Test]
    public void IsAdult_should_be_true_for_customer_having_age_20()
    {
        var sut = new CustomerValidator();            
        int greaterThanAge = 20;

        var result = sut.IsAdult(greaterThanAge);

        Assert.IsTrue(result);
    }
}

如果你真的想测试客户,那么再写一个测试

[TestFixture]
public class CustomerTests
{

    [Test]
    public void IsCustomerAdult_verifyIsAdultIsCalled()
    {
        var mock = new Mock<ICustomerValidator>();
        var sut = new Customer(mock.Object);

        var result = sut.IsCustomerAdult();

        mock.Verify(x => x.IsAdult(It.IsAny<int>()));
    }
}

在这些琐碎的测试中,您不需要 AutoMocking。

于 2014-11-27T11:11:04.967 回答