Moq一个类并仍然使用它的方法

3
我正在使用Moq框架对一个类进行模拟。然而,我无法调用该类的方法。如何解决下面的单元测试中出现的问题?尝试编译程序以在类中提取Moq中的方法。以下是错误信息:

类:

using System;
using ElectronicsStore.Models;
using Microsoft.Extensions.Logging;

namespace ElectronicsStore.Service
{
    public class ParseVendorSupply
    {
        private readonly ILogger _logger;

        public ParseVendorSupply(ILogger logger)
        {
            _logger = logger;
        }

        public VendorSupply FromCsv(string csvLine)
        {
            VendorSupply vendorsupply = new VendorSupply();

            try
            {
                string[] values = csvLine.Split(',');
                if (values.Length > 3)
                {
                    throw new System.ArgumentException("Too much data");
                }

                vendorsupply.VendorId = Convert.ToInt16(values[0]);
                vendorsupply.ProductId = Convert.ToInt16(values[1]);
                vendorsupply.Quantity = Convert.ToInt16(values[2]);
            }
            catch (Exception)
            {
                _logger.LogInformation("An exception was thrown attempting");
            }
            return vendorsupply;
        }       
    }
}

public Startup(IConfiguration configuration, ILogger<Startup> logger)
{
    Configuration = configuration;
    _logger = logger;
 }

public void ConfigureServices(IServiceCollection services)
{
     services.AddSingleton(new LoggerFactory().AddConsole().AddDebug());
     services.AddLogging();

NUnit测试:

public class ParseVendorSupplyNunit
{

    [Test]
    public void FromCsv_ParseCorrectly_Extradata()
    {
        var logger = new Mock<ILogger>();
        Mock<ParseVendorSupply> parseVendorSupplytest = new Mock<ParseVendorSupply>(logger);
        var test = new Mock<ParseVendorSupply>(logger);
        string csvLineTest = "5,8,3,9,5";

       parseVendorSupplytest.FromCsv
       // Receive error: Mock<ParseVendorSupply>' does not contain a definition for 'FromCsv' and no accessible extension method 'FromCsv' accepting a first argument of type 'Mock<ParseVendorSupply>' could be found (are you missing a using directive or an assembly reference?)

    }
1个回答

1
Moq通过.Object属性公开模拟对象。因此在您的情况下,您可以执行以下操作:
parseVendorSupplytest.Object.FromCsv(csvLineTest);

话虽如此,我不确定这是否是你最初想要做的。假设你正在尝试使用模拟记录器测试ParseVendorSupply,我认为你的代码应该如下所示:
[Test]
public void FromCsv_ParseCorrectly_Extradata()
{
    var logger = new Mock<ILogger>();
    var parseVendorSupply = new ParseVendorSupply(logger.Object);

    string csvLineTest = "5,8,3,9,5";

    var result = parseVendorSupplytest.FromCsv(csvLineTest);

   // Add your assertions here 
}

此外,请注意,如果您不需要任何设置,您可以使用Mock.Of<T>()快捷方式直接检索模拟对象:
var parseVendorSupply = new ParseVendorSupply(Mock.Of<ILogger>());

不知为何,在添加记录器和模拟框架之前,单元测试通过了。但现在收到消息:“预期:<System.ArgumentException> ,实际却是:未抛出异常",然而我调试时确实抛出了异常。 - user10634744
@JoeThomas 你需要展示一些代码来解释:p 异常被捕获在你的 ParseVendorSupply.FromCsv 方法中,那么你的断言看起来是什么样子的? - Kevin Gosse

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接