简体   繁体   English

如何使用 It.IsAny<>(TValue) 来匹配对象的某些属性?

[英]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);

c# xUnit Moq It.IsAny<object> 没有像预期的那样嘲笑<div id="text_translate"><p>以下是一段代码(简单的 HTTP post 调用),我试图在 Azure 函数中模拟:</p><pre> await httpClient.PostAsync("https://url.com", await File.ReadAllTextAsync(Path.Combine(Environment.GetEnvironmentVariable("APP_DIRECTORY"), "file.json"));</pre><p> 请注意,httpClient.PostAsync() 函数有两个参数:URL 作为字符串,body 作为对象。</p><p> 现在,在我的测试中,我像这样模拟这个 POST 调用:</p><pre> httpClientMock.Setup(s =&gt; s.PostAsync(It.IsAny&lt;string&gt;(), It.IsAny&lt;object&gt;())).ReturnsAsync(mockedHttpResponse);</pre><p> 我期待await File.ReadAllTextAsync(Path.Combine(Environment.GetEnvironmentVariable("APP_DIRECTORY"), "file.json")不会被调用,因为我将它设置为与任何对象一起工作。但是,我的测试用例失败了例外:</p><blockquote><p> 在 System.IO.Path.Combine(String path1, String path2) 处发现 System.ArgumentNullException 消息“Value cannot be null. (Parameter 'path1')”</p></blockquote><p> 当我通过在测试中设置环境变量来提供正确的路径(即使是虚拟路径也不起作用)时,它就起作用了。 但这似乎不是正确的方法,因为单元测试旨在在各种机器上运行,并且每台机器的基本路径都不同。</p></div></object> - c# xUnit Moq It.IsAny<object> not mocking as expected

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我如何使用It.IsAny作为参数? - How can I use It.IsAny as a parameter? 是否存在 It.IsAny 不匹配值的情况? - Are there cases where It.IsAny does not match a value? It.IsAny <T>()用作模拟对象 - It.IsAny<T>() used as a mocked object Moq的It.IsAny怎么样? <T> ()实施 - How is Moq's It.IsAny<T>() implemented 如果我可以定义一个变量,为什么要使用 It.is&lt;&gt; 或 It.IsAny&lt;&gt;? - Why use It.is<> or It.IsAny<> if I could just define a variable? mock.setup It.IsAny 或 It.Is 代替 new object() - mock.setup It.IsAny or It.Is instead new object() c# xUnit Moq It.IsAny<object> 没有像预期的那样嘲笑<div id="text_translate"><p>以下是一段代码(简单的 HTTP post 调用),我试图在 Azure 函数中模拟:</p><pre> await httpClient.PostAsync("https://url.com", await File.ReadAllTextAsync(Path.Combine(Environment.GetEnvironmentVariable("APP_DIRECTORY"), "file.json"));</pre><p> 请注意,httpClient.PostAsync() 函数有两个参数:URL 作为字符串,body 作为对象。</p><p> 现在,在我的测试中,我像这样模拟这个 POST 调用:</p><pre> httpClientMock.Setup(s =&gt; s.PostAsync(It.IsAny&lt;string&gt;(), It.IsAny&lt;object&gt;())).ReturnsAsync(mockedHttpResponse);</pre><p> 我期待await File.ReadAllTextAsync(Path.Combine(Environment.GetEnvironmentVariable("APP_DIRECTORY"), "file.json")不会被调用,因为我将它设置为与任何对象一起工作。但是,我的测试用例失败了例外:</p><blockquote><p> 在 System.IO.Path.Combine(String path1, String path2) 处发现 System.ArgumentNullException 消息“Value cannot be null. (Parameter 'path1')”</p></blockquote><p> 当我通过在测试中设置环境变量来提供正确的路径(即使是虚拟路径也不起作用)时,它就起作用了。 但这似乎不是正确的方法,因为单元测试旨在在各种机器上运行,并且每台机器的基本路径都不同。</p></div></object> - c# xUnit Moq It.IsAny<object> not mocking as expected 如何使用 It.IsAny AddItemFactory 函数模拟 IAppCache 的 GetOrAddAsync 方法 - How to mock IAppCache's GetOrAddAsync method with It.IsAny AddItemFactory function 如何将表达式签名转换为适用于Moq的It.IsAny的表达式 - How to convert expression signature to be applicable with `It.IsAny` of `Moq` 如何简化 It.IsAny<t> () 用于设置 Mocks 的参数</t> - How to simplify the It.IsAny<T>() parameters for setting up Mocks
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM