문제

나는 MOQ에서 이상한 행동을 경험하고있다 - 나는 특정 방식으로 행동하기 위해 모의 개체를 설정 한 다음 테스트하는 객체에서 정확히 같은 방식으로 메소드를 호출한다는 사실에도 불구하고, 방법이 마치 마치 마치 반응한다. 전화하지 않았습니다.

테스트하려는 다음 컨트롤러 동작이 있습니다.

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

내 단위 테스트 코드 :

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>
    );
}

어디 AssertThat 많은 주장 도우미가있는 내 자신의 클래스 일뿐입니다. Assert 확장 방법으로 클래스를 확장 할 수 없습니다 ... 한숨 ...).

테스트를 실행하면 실패합니다. repository.Verify() 라인, a MoqVerificationException:

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 코드가 실행되는 위치를 차단하십시오. 거기에 문제가 없습니다.

왜 이것이 효과가 없습니까?

도움이 되었습니까?

해결책

조롱 된 저장소에 전달하는 배열 (결과 teststring.Split(' '))는 실제로 검색 방법에서 전달되는 것과 동일한 대상이 아닙니다 (결과) query.Split(' ')).

설정 코드의 첫 번째 줄을 다음과 같이 대체하십시오.

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

... 통과 된 배열의 각 요소를 모의에 비교할 것입니다. keywords 정렬.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top