我想模拟一个方法,但我的方法是在条件下,我需要的值是真的,这个操作使我的测试通过,如果我不模拟我的方法,它给我空异常,所以这很重要

  [Test]
    public void Can_return_price_according_to_semester_status()
    {
        var product = new Product
        {
            ProductTypeId = 15,
            Id = 1,
            Name = "Product name 1",
            Price = 12.34M,
            CustomerEntersPrice = false,
            Published = true,
            PreRegistrationPrice = 10.99M
        };

        _productService.Setup(x => x.GetSemesterProductTypeIds(It.IsAny<int[]>())
        .Contains(product.ProductTypeId)).Returns(true);// this is my target mock



        var customer = new Customer();
        _priceCalcService.GetFinalPrice(product, customer, 0, false, 1).ShouldEqual(product.Price);
        _priceCalcService.GetFinalPrice(product, customer, 0, false, 1).ShouldEqual(product.PreRegistrationPrice);
    }

GetFinalPrice:

    if (_productService.GetSemesterProductTypeIds().Contains(product.ProductTypeId))// this is target of my mock
            {
                if (enrollmentTypeId <= 0)
                {
                    if (product.SemesterStatus == SemesterStatus.PreRegistration)
                    {
                        enrollmentTypeId = (int)EnrollmentType.PreRegistered;
                    }
                }
                if (enrollmentTypeId == (int)EnrollmentType.PreRegistered)
                {
                    price = product.PreRegistrationPrice;
                }
            }// some operation after this

problem

推荐答案

模拟GetSemesterProductTypeIds()调用比模拟Contains()方法更有意义.

让您的产品id返回GetSemesterProductTypeIds()作为示例.

_productService
    .Setup(x => x.GetSemesterProductTypeIds(It.IsAny<int[]>())
    .Returns(new List<int> { 15 });

Csharp相关问答推荐

Should. ThrowAsynock未捕获来自httpClient. GetAsynock()请求的异常

.NET通过版本自动增量设置包版本

ß != ss与ICU进行不区分大小写的比较

获取ASP.NET核心身份认证cookie名称

C#中使用BouncyCastle计算CMac

安装附加的. exe与Visual Studio

如果属性名为xyz,我需要使用System.Text.Json修改字符串类型的值""<>

Docker Container中的HttpRequest后地址不可用

如何使用MailKit删除邮箱?

GODOT 4向C#中的字符串参数发送信号以等待

如何更改新创建的实例的变量?

如何在.NET Maui中将事件与MVVM一起使用?

MSI无法将快捷方式添加到启动文件夹

如何使用Npgsql从SELECT获得所有查询结果

未在Windows上运行的Maui项目

Xamarin.Forms中具有类似AspectFill的图像zoom 的水平滚动视图

C#中COM对象的实际地址

.NET文档对继承的困惑

反序列化我以前使用System.Text.Json序列化的文件时出现异常

ASP.NET核心MVC|如何在控制器方法之间传递值