简体   繁体   English

ASP.net Core MVC 测试/使控制器返回一个字符串?

[英]ASP.net Core MVC testing / make controller return a string?

I'm currently at the point where I want to write a test for my ASP.net Core MVC project.我目前正想为我的 ASP.net Core MVC 项目编写测试。

The problem is that I currently put this code into my view, which isn't really suitable for testing.问题是我目前将此代码放入我的视图中,这并不适合测试。

A snippet of the code is as follow:代码片段如下:

@if (Model.MealDays != null)
{
    bool boolSaltLess = false;

        @foreach (var c in Model.MealDays)
        {
                @{
                    if (@c.Meal.Saltless == true)
                    {
                        boolSaltLess = true;
                    }
                }
        }
    <div>
        <p><b>Missing meal diets:</b></p>
        @if (boolSaltLess == false)
        {
            <p style="color:red">A saltless meal!</p>
        }
   </div>
}

My initial question is if I could move this code into my controller, and what result I would need to return from my controller to display this information in my View.我最初的问题是我是否可以将此代码移动到我的控制器中,以及我需要从控制器返回什么结果才能在我的视图中显示此信息。

    public ViewResult DayDetail(int id)
    {
        Day d = repository.Days.Where(Day => Day.ID == id).FirstOrDefault();
        IEnumerable<MealDay> md = mdRepository.MealDays;

        foreach (MealDay i in md)
        {
            i.Day = repository.Days.Where(Day => Day.ID == i.DayID).FirstOrDefault();
            i.Meal = mRepository.Meals.Where(Meal => Meal.ID == i.MealID).FirstOrDefault();

        }

        return View(d);
    }

Include an additional property in the view model to pass the data to the view在视图模型中包含一个附加属性以将数据传递给视图

public bool Saltless { get; set; }

Move the logic into the controller action and将逻辑移到控制器动作中

//...

model.Saltless = model.MealDays?.Any(c => c.Meal.Saltless);

return View(model);

//...

In the view, now it is a simple matter of check the property在视图中,现在检查属性是一件简单的事情

@if (Model.MealDays != null) {    
    <div>
        <p><b>Missing meal diets:</b></p>
    @if (Model.Saltless == false)
    {
        <p style="color:red">A saltless meal!</p>
    }
    </div>
}

And it allows the logic to be verified via unit tests on the Controller action它允许通过对 Controller 操作的单元测试来验证逻辑

The logic is unnecessary in the first place.首先,逻辑是不必要的。 Just do:做就是了:

@if (!Model.MealDays.Any(x => x.Meal.Saltless))
{
    <p style="color:red">A saltless meal!</p>
}

Besides, tests are about results, not logic or implementation.此外,测试是关于结果的,而不是逻辑或实现。 In other words, the test passes if when all the meals are saltless, the response contains "A saltless meal!"换句话说,如果当所有食物都无盐时,响应包含“无盐食物!”,则测试通过。 and doesn't if any of the meals are saltless.如果任何一餐都是无盐的,则不会。 That means whatever logic you had works, and that's all that matters.这意味着你的任何逻辑都有效,这才是最重要的。

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

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