2009-08-16 4 views
9

내 모의 개체에서 메서드 호출에 대한 기대치를 설정할 때 Ienumerable/Array 형식 매개 변수를 확인하는 데 문제가 있습니다. 나는 그것을 그것이 매치로 간주하지 않는 다른 참조와 일치하기 때문에 생각한다. 배열의 내용과 일치시키기를 원할 때가 있습니다. 때로는 순서에 대해서도 신경 쓰지 않습니다.Moq 일치 및 메서드 설정의 배열/IEnumerable 매개 변수

mockDataWriter.Setup(m => m.UpdateFiles(new string[]{"file2.txt","file1.txt"})); 

이상적으로는 다음과 같이 작동하는 것이 이상적입니다.이 작업을 수행하는 확장 메서드를 작성할 수 있습니다.

It.Contains(new string[]{"file2.txt","file1.txt"}) 

It.ContainsInOrder(new string[]{"file2.txt","file1.txt"}) 
(가) 유일한 방법은 내장

나는이 바로 지금 술어 기능이지만,이 문제는 충분히 일반이 내장되어야 보인다 일치시킬 수 있습니다.

이 방법으로 만들어진이 일치하는 것입니다 이러한 유형 또는 확장 라이브러리를 사용할 수 있습니다. 그렇지 않다면 확장 메소드 등을 작성합니다.

덕분에 일부 사용자 지정 매처 (matcher)를 구현했다

+1

이 질문/대답은 전혀 도움이된다면보기 : http://stackoverflow.com/questions/1220013/expectation-on-mock-object-doesnt-seem-to -be-met-moq –

답변

7

는 자원으로 http://code.google.com/p/moq/wiki/QuickStart을 사용하는 버전 3에서이 작업을 수행하는 방법에 내장 기타를 발견하지 않았습니다.

public T[] MatchCollection<T>(T[] expectation) 
{ 
    return Match.Create<T[]>(inputCollection => (expectation.All((i) => inputCollection.Contains(i)))); 
} 

public IEnumerable<T> MatchCollection<T>(IEnumerable<T> expectation) 
{ 
    return Match.Create<IEnumerable<T>>(inputCollection => (expectation.All((i) => inputCollection.Contains(i)))); 
} 


public void MyTest() 
{ 

... 

mockDataWriter.Setup(m => m.UpdateFiles(MatchCollection(new string[]{"file2.txt","file1.txt"}))); 

... 


} 
+0

예상되는 모든 값이 inputCollection에 있는지 아닌지를 확인합니다. inputCollection에는 여전히 예상과 다른 항목이 포함될 수 있습니다. –

3

당신은 배열을 IEnumerable을위한 두 개의 별도의 방법을 필요가 없습니다 inputCollectionexpectation에없는 요소가있는 경우 올렉에 의해

private static IEnumerable<T> MatchCollection<T>(IEnumerable<T> expectation) 
{ 
    return Match.Create<IEnumerable<T>>(inputCollection => expectation.All(inputCollection.Contains)); 
} 
4

이전 대답이 사건을 처리하지 않습니다. 예를 들어

:

MatchCollection(new [] { 1, 2, 3, 4 }) 

이 inputCollection { 1, 2, 3, 4, 5 } 일치 할 때 명확하게해야하지.

여기 완전한 정규이다 :

public static IEnumerable<T> CollectionMatcher<T>(IEnumerable<T> expectation) 
{ 
    return Match.Create((IEnumerable<T> inputCollection) => 
         !expectation.Except(inputCollection).Any() && 
         !inputCollection.Except(expectation).Any()); 
} 
+0

특별한 케이스 취급에 감사드립니다. – saxos