2009-08-02 2 views
3

Moq에서 이상한 동작이 발생합니다. 모의 객체를 특정 방식으로 작동하도록 설정했지만 정확한 방법으로 메소드를 호출 했음에도 불구하고 테스트중인 객체에서와 같은 방식으로 메서드가 호출되지 않은 것처럼 반응합니다.모의 객체에 대한 기대가 충족되지 않는 것 같습니다 (Moq)

I가 내가 시험에 노력하고있어 다음 컨트롤러 액션 :

public ActionResult Search(string query, bool includeAll) 
{ 
    if (query != null) 
    { 
     var keywords = query.Split(' '); 
     return View(repo.SearchForContacts(keywords, includeAll)); 
    } 
    else 
    { 
     return View(); 
    } 
} 

내 단위 테스트 코드 : AssertThat가의 무리와 내 자신의 단지 클래스입니다

public void SearchTestMethod() // Arrange 
    var teststring = "Anders Beata"; 
    var keywords = teststring.Split(' '); 
    var includeAll = false; 
    var expectedModel = dummyContacts.Where(c => c.Id == 1 || c.Id == 2); 
    repository 
     .Expect(r => r.SearchForContacts(keywords, includeAll)) 
     .Returns(expectedModel) 
     .Verifiable(); 

    // Act 
    var result = controller.Search(teststring, includeAll) as ViewResult; 

    // Assert 
    repository.Verify(); 
    Assert.IsNotNull(result); 
    AssertThat.CollectionsAreEqual<Contact>(
     expectedModel, 
     result.ViewData.Model as IEnumerable<Contact> 
    ); 
} 

단언 도우미 (Assert 클래스는 확장 메서드로 확장 될 수 없기 때문에 ...). 내가 테스트를 실행하면

, 그것은 MoqVerificationException과 함께 repository.Verify() 줄에 실패

Test method MemberDatabase.Tests.Controllers.ContactsControllerTest.SearchTestMethod() 
threw exception: Moq.MockVerificationException: The following expectations were not met: 
IRepository r => r.SearchForContacts(value(System.String[]), False)

내가 repository.Verify() 제거하는 경우, 수집 어설 반환 모델이 null 것을 말해 실패합니다. 내가 디버그하고 체크 그 query != null, 그리고 코드의 실행 블록 if의 일부로 찍은 오전. 거기에 문제 없습니다.

왜 작동하지 않습니까?

답변

6

모의 저장소에 전달하려는 배열 (teststring.Split(' ')의 결과)이 실제로 검색 방법에서 전달 된 객체 (query.Split(' ')의 결과)와 다른 객체라고 생각됩니다. 로 설정 코드의 첫 번째 라인을 교체

시도해보십시오 keywords 배열의 해당 요소로 모의에 전달 된 배열의 각 요소를 비교합니다

repository.Expect(r => r.SearchForContacts(
    It.Is<String[]>(s => s.SequenceEqual(keywords)), includeAll)) 

....

+0

고마워요! 그 트릭을 immeditely 않았다! =) 그것은 Moq에 대해서, 특히 It ... 구조체를 사용할시기와 방법에 대해 읽어야 할 것 같습니다. –

관련 문제