[英]How to use It.IsAny<>(TValue) to match some properties of an object?
Consider following code.考虑以下代码。 It has
BookingRequest
which contains two properties.它有包含两个属性的
BookingRequest
。 Interface IBookingRequestProcessor
has a method to process BookingRequest
.接口
IBookingRequestProcessor
有一个方法来处理BookingRequest
。 I want to create mocks which would match all BookingRequest
object that match one property but other property can be any value.我想创建将匹配所有匹配一个属性但其他属性可以是任何值的
BookingRequest
对象的BookingRequest
。
For that I created mock matched object with matching properties set to values I want to match and other properties set to It.IsAny<>()
.为此,我创建了模拟匹配对象,匹配属性设置为我想要匹配的值,其他属性设置为
It.IsAny<>()
。 However, I get Moq.MockException
with reason as All invocations on the mock must have a corresponding setup.
但是,我得到
Moq.MockException
有原因的,因为All invocations on the mock must have a corresponding setup.
. .
The complete code is as:完整代码如下:
using System;
using Moq;
public class Program {
public class BookingRequest
{
public string FlightId { get; set; }
public string BookingId { get; set; }
public BookingRequest() { }
public BookingRequest(string FlightId, string BookingId)
{
this.FlightId = FlightId;
this.BookingId = BookingId;
}
}
public interface IBookingRequestProcessor
{
string ConstantReturn(string param);
int ProcessBooking(BookingRequest bookingRequest);
}
public static void Main(String[] args) {
var bookingRequestMock = new Mock<IBookingRequestProcessor>(MockBehavior.Strict);
bookingRequestMock
.Setup(bp => bp.ConstantReturn(It.IsAny<string>()))
.Returns("AB");
Console.WriteLine(bookingRequestMock.Object.ConstantReturn(Guid.NewGuid().ToString()));
Console.WriteLine("----");
var bookingRequestMatcher = new BookingRequest()
{
FlightId = "AB495",
BookingId = It.IsAny<string>()
};
bookingRequestMock
.Setup(bp => bp.ProcessBooking(bookingRequestMatcher))
.Returns(495);
var bookingRequest = new BookingRequest("AB495", Guid.NewGuid().ToString());
Console.WriteLine(bookingRequest.FlightId + " --> " + bookingRequestMock.Object.ProcessBooking(bookingRequest));
}
}
Matching for mocked object properties have to be handled via Is<TValue>()
.必须通过
Is<TValue>()
处理模拟对象属性的匹配。 You can match based on required properties in following way:您可以通过以下方式根据所需的属性进行匹配:
bookingRequestMock
.Setup(bp => bp.ProcessBooking(It.Is<BookingRequest>(br => br.FlightId == "AB495")))
.Returns(495);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.