简体   繁体   中英

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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