我是Autofac的初学者。我最初创建了一个示例项目,然后用构造函数注入替换了所有new()关键字。然后用Autofac替换构造函数注入,项目工作正常。
我的问题: 我有我的单元测试用例,我将参数传递给构造函数,因为我用Autofac替换了我的项目。我不确定如何更换单元测试用例构造函数注入以使用Autofac。
public class GenericHelper : IGenericHelper
{
private IDAL _DAL;
private IDate _Date;
//public GenericHelper(IDAL DAL,IDate Date) /* Constructor injection */
//{ _DAL = DAL;
// _Date = Date;
//}
public String CalculateMatruity(IAge AgeObj)
{
String Maturity = "", AgeConfiguration;
//IDAL dalObj = _DAL;
//IDate dateObj = _Date;
var builder = new ContainerBuilder();
builder.RegisterType<AgeDAL>().As<IDAL>();
builder.RegisterType<CurrentDate>().As<IDate>();
using (var container = builder.Build())
{
// AgeConfiguration = dalObj.GetMaturityConfiguration(); /* initial approach */
AgeConfiguration = container.Resolve<IDAL>().GetMaturityConfiguration();
//Int64 Age = dateObj.Date.Year - AgeObj.Birthdate.Year; /* initial approach */
var _d = container.Resolve<IDate>().Date.Year;
Int64 Age = _d - AgeObj.Birthdate.Year; /* Using autofac approach */
var config = AgeConfiguration.Split('|').Select(s => s.Split('=')).ToDictionary(c => c[1], c => int.Parse(c[0]));
............
我的错误单元测试:
[TestMethod]
public void TestGenericHelper()
{
Person age = new Person();
age.Birthdate = DateTime.Parse("1987-06-16");
String expected = "Teen";
DateTime FakeDate = Convert.ToDateTime("2000-01-01");
String fake = "0=Child|13=Teen|18=Adult";
FakeDate DateHelperObj = new FakeDate(FakeDate);
FakeAgeDAL fakeObj = new FakeAgeDAL(fake);
GenericHelper GenericHelperObj = new GenericHelper(fakeObj, DateHelperObj); /* I Need to replace it use Autofac */
String actual = GenericHelperObj.CalculateMatruity(age);
Assert.AreEqual(expected, actual);
}
我需要替换GenericHelper类实例以使用autofac但是调用虚拟对象。任何人都可以请教。
由于