2017-12-02 185 views
1

我有一个类,它在一个IMapper在构造这样存根或模拟IMapper返回派生类,其中基地预期

public Foo(IMapper mapper) 

在代码Foo的我有此线

var dao = _mapper.Map<BaseDAO>(obj); 

BaseDAO有3个子类型,在我已经设置的实际代码中这样

CreateMap<Base, BaseDAO>() 
    .Include<Child1, Child1DAO>() 
    .Include<Child2, Child2DAO>() 
    .Include<Child3, Child3DAO>(); 

我想模拟出上述行

var dao = _mapper.Map<BaseDAO>(obj); 

因此如果Child1在随后被传递一个Child1DAO将返回与同为其他亚型。我试图存根出IMapper但下面的方法返回一个错误,指出

Child1DAO不能被隐式转换为TDestination

,我试图模拟出IMapper但未能得到这两种工作。

public TDestination Map<TDestination>(object source) 
{ 
    return new Child1DAO(); 
} 

任何想法?

回答

1

对于这个例子的目的,假设以下类是下测试受试者

public class Foo { 
    private IMapper mapper; 
    public Foo(IMapper mapper) { 
     this.mapper = mapper; 
    } 

    public BaseDAO Bar(object obj) { 
     var dao = mapper.Map<BaseDAO>(obj); 
     return dao; 
    } 
} 

IMapper依赖性具有以下合同定义

public interface IMapper { 
    /// <summary> 
    /// Execute a mapping from the source object to a new destination object. 
    /// The source type is inferred from the source object. 
    /// </summary> 
    /// <typeparam name="TDestination">Destination type to create</typeparam> 
    /// <param name="source">Source object to map from</param> 
    /// <returns>Mapped destination object</returns> 
    TDestination Map<TDestination>(object source); 

    //... 
} 

下面的试验证明了,使用起订,

模拟IMapper返回派生类,其中基地期望d

[TestClass] 
public class TestClass { 
    [TestMethod] 
    public void _TestMethod() { 
     //Arrange 
     var mock = new Mock<IMapper>(); 
     var foo = new Foo(mock.Object); 

     mock 
      //setup the mocked function 
      .Setup(_ => _.Map<BaseDAO>(It.IsAny<object>())) 
      //fake/stub what mocked function should return given provided arg 
      .Returns((object arg) => { 
       if (arg != null && arg is Child1) 
        return new Child1DAO(); 
       if (arg != null && arg is Child2) 
        return new Child2DAO(); 
       if (arg != null && arg is Child3) 
        return new Child3DAO(); 

       return null; 
      }); 

     var child1 = new Child1(); 

     //Act 
     var actual = foo.Bar(child1); 

     //Assert 
     Assert.IsNotNull(actual); 
     Assert.IsInstanceOfType(actual, typeof(BaseDAO)); 
     Assert.IsInstanceOfType(actual, typeof(Child1DAO)); 
    } 
}