简体   繁体   English

Moq 如何验证通用功能参数?

[英]How does Moq verify Generic Func Parameter?

Given给定

public interface IService
{
  void Run<T>(T value, Func<T, string> func);
}

public class Sut
{
  private readonly IService m_service;

    public Sut(IService service)
    {
        m_service = service;
    }

    public void Test()
    {
        Point point = new Point {X = 1, Y = 2};
        m_service.Run(point, p => $"X:{p.X}, Y:{p.Y}");
    }
}

internal class Point
{
    public int X { get; set; }
    public int Y { get; set; }
}

And tested like并经过测试

[Test]
public void RunTest()
{
    // Arrange
    Mock<IService> mockService = new Mock<IService>();
    var sut = new Sut(mockService.Object);

    // Act
    sut.Test();

    // Assert
    mockService.Verify(e => e.Run(It.IsAny<It.IsAnyType>(), It.IsAny<Func<It.IsAnyType, string>>()), Times.Once);
}

This test will failed, due to Point is third party internal class, I can not use It.IsAny<Point> in the verify.此测试将失败,由于 Point 是第三方内部 class,我无法在验证中使用It.IsAny<Point>

if I change the Point to the public and verify use following, it's working good.如果我将 Point 更改为 public 并验证以下使用情况,它运行良好。

mockService.Verify(e => e.Run(It.IsAny<Point>(), It.IsAny<Func<Point, string>>()), Times.Once);

any help would be appreciated任何帮助,将不胜感激

Generally, you want to put an InternalsVisibleTo attribute in the assembly under test, pointing to the test assembly.通常,您希望在被测程序集中放置一个InternalsVisibleTo属性,指向测试程序集。

See here for reference information.有关参考信息,请参见此处

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM