2017-12-02 24 views
1

나는이 선을 푸의 코드에서이스텁 또는 모의 IMapper는

public Foo(IMapper mapper) 

처럼 생성자에 IMapper에 걸리는 클래스가있다

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

는 다음과 같은 클래스를 가정하는 것은 MOQ를 사용하여, 다음 테스트가 보여 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); 

    //... 
} 

을 정의한 시험 대상

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 기본 기대어 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)); 
    } 
}