我如何模拟从父对象返回的所有对象在同一调用上

时间:2019-04-17 12:14:43

标签: c# unit-testing mocking moq

这是我具体方法中的代码行:

var patron = patronService.GetPatron(new GetPatronRequest() { PatronId = request.PatronId }).Patron;

我的GetPatron方法返回一个GetPatronResponse对象,该对象上声明了一个Patron对象。

到目前为止,这是我的TestMethod

[TestMethod]
public void WhenGetPatronPropertyPricingIsCalled_ThenGetPatronPropertyPricingResponseIsReturned()
{
    // Given
    var request = new GetPatronPropertyPricingRequest
    {
         PatronId = "1",
         ServiceCodes = new List<string> { "1" }
    };

    var repo = new Mock<IPatronPropertyPricingServiceRepository>();
    var patronService = new Mock<IPatronsService>();
    var patronPropertyPrice = new PatronPropertyPrice() { CurrencySymbol = "£", ServiceCode = "1", MinimumPrice = 5.00m, MaximumPrice = 10.00m };
    var patronResponse = new GetPatronResponse(new GetPatronRequest());
    var patronRequest = new GetPatronRequest(){ PatronId = "1"};
   // patronService.Setup(x => x.GetPatron(It.IsAny<GetPatronRequest>()).Patron).Returns(patronResponse.Patron);

    patronService.Setup(x => x.GetPatron(It.IsAny<GetPatronRequest>()).Patron).Returns(It.IsAny<Patron>());
    // patronService.Object.GetPatron(new GetPatronRequest() {PatronId = request.PatronId});
    // patronPropertyPrice.Setup(tt => new PatronPropertyPrice() { CurrencySymbol = "£", ServiceCode = "1", MinimumPrice = 5.00m, MaximumPrice = 10.00m });
    repo.Setup(repository => repository.GetPropertyPricing(request.PatronId)).Returns(patronPropertyPrice);

    var svc = new PersistingPatronPropertyPricingService(repo.Object,patronService.Object);

    // When
    var response = svc.GetPropertyPricing(request);

    // Then
    Assert.AreEqual(patronPropertyPrice, response.PatronPropertyPrices);
}

我在具体方法中尝试执行的操作始终会在我尝试设置响应时返回一个未设置错误的对象,或者对非虚拟错误进行无效设置。

1 个答案:

答案 0 :(得分:2)

我假设GetPatron返回带有PatronResponse属性的类似Patron的内容。

在这种情况下更改

patronService.Setup(x => x.GetPatron(It.IsAny<GetPatronRequest>()).Patron).Returns(It.IsAny<Patron>());

var patronResponse = new PatronResponse { Patron = new Patron() };
patronService
    .Setup(x => x.GetPatron(It.IsAny<GetPatronRequest>()))
    .Returns(patronResponse);

It.IsAny<T>()用于设置表达式,而不是变量。