Consider following code. It has BookingRequest which contains two properties. Interface IBookingRequestProcessor has a method to process BookingRequest. I want to create mocks which would match all BookingRequest object that match one property but other property can be any value.
For that I created mock matched object with matching properties set to values I want to match and other properties set to It.IsAny<>(). However, I get Moq.MockException with reason as 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>(). You can match based on required properties in following way:
bookingRequestMock
.Setup(bp => bp.ProcessBooking(It.Is<BookingRequest>(br => br.FlightId == "AB495")))
.Returns(495);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With