2014-09-04 17 views
1

MEF (System.ComponentModel.Composition)를 사용하면 컨테이너에 모의 객체를 추가 할 수 있습니다.MEF 2 (System.Composition)를 사용할 때 WebApi 2 컨트롤러의 종속성을 모방하는 방법은 무엇입니까?

container.ComposeExportedValue(mock.Object); 

심판 : How to use Moq to satisfy a MEF import dependency for unit testing?

방법이 휴대용 MEF 라이브러리 (System.Composition)로 가능하다?

더 많은 문맥을 위해 나는 지금까지 가지고있는 많은 코드를 게시 할 것이다.

메모리 내 ASP.NET Web API을 통해 xBehave.net 통합 테스트를 만들고 있습니다.

이렇게 클라이언트를 설정했습니다.

config = new HttpConfiguration(); 
WebApiConfig.Register(config); 
config.DependencyResolver = MefConfig(); 
server = new HttpServer(config); 
Client = new HttpClient(server); 
Request = new HttpRequestMessage(); 

WebApiContrib.IoC.Mef의 기본값처럼 내 MEF 구성을 설정했습니다.

private static IDependencyResolver MefConfig() 
{ 
    var conventions = new ConventionBuilder(); 
    conventions.ForTypesDerivedFrom<IHttpController>().Export(); 
    conventions.ForTypesMatching(
     t => t.Namespace != null && t.Namespace.EndsWith(".Parts")) 
     .Export() 
     .ExportInterfaces(); 

    var container = new ContainerConfiguration() 
     .WithAssemblies(
      new[] { Assembly.GetAssembly(typeof(ICache)) }, conventions) 
     .CreateContainer(); 

    return new MefDependencyResolver(container); 
} 

다음은 테스트하려는 컨트롤러의 서명입니다. 캐시에서 읽습니다.

public MyController(ICache cache) { } 

다음은 테스트입니다. 모의는 Moq으로 생성됩니다.

[Scenario] 
public void RetrieveOnPollingRequest() 
{ 
    const string Tag = "\"tag\""; 
    string serverETag = ETag.Create(Tag); 

    "Given an If-None-Match header" 
     .f(() => Request.Headers.IfNoneMatch.Add(
      new EntityTagHeaderValue(Tag))); 
    "And the job has not yet completed" 
     .f(() => 
      { 
       string tag = serverETag; 
       this.MockCache.Setup(x => x.StringGet(tag)).Returns(Tag); 
      }); 
    "When retrieving jobs" 
     .f(() => 
      { 
       Request.RequestUri = uri; 
       Response = Client.SendAsync(Request).Result; 
      }); 
    "Then the status is Not-Modified" 
     .f(() => 
      Response.StatusCode.ShouldEqual(HttpStatusCode.NotModified)); 
} 

그럼 이미 내 보낸 부품 대신 해당 모의품을 컨테이너에 어떻게 가져 옵니까? 아니면 내가? 다른 IoC 컨테이너를 사용해야합니까?

답변

1

MEF CodePlex 사이트의 Microsoft.Composition.Demos.ExtendedPartTypes 샘플에서 수행 한 방법을 사용하여이를 수행 할 수 있습니다.

var container = new ContainerConfiguration() 
    .WithExport<IAmMocked>(mockObject) 
    .WithAssemblies(
     new[] { Assembly.GetAssembly(typeof(ICache)) }, conventions) 
    .CreateContainer(); 

당신은 여기에 전체 코드를 찾을 수 있습니다 : 다음 IAmMocked 서비스 인스턴스 mockObject를 등록 보여주는 아래 http://mef.codeplex.com/SourceControl/latest#oob/demo/Microsoft.Composition.Demos.ExtendedPartTypes/Program.cs

우리는 어떤 점에서 "상자에"이 얻을 것이 아니라 난 몰라 그것이 일어난 것을 믿으십시오. 달리기에 문제가 있으면 알려주세요!

+0

그 덕분에, 고마워요. 테스트 스위트를 위해 내 보낸 모의 객체로 하나의 테스트 컨테이너를 설정 한 다음 테스트 케이스에 따라 모의 객체를 수정할 수있다. – Boggin