我正在使用 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());
}
}
}