2017-12-02 231 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)); 
    } 
}