0

So I have a controller "ItemsController" that I have to create a Unit Test case for in NUnit.

But I have no idea how to get it working since it extends the Base Controller that only has a get method and no setter, so any test I run throws an error cause the "Container" is null. I can't create the Set Method because it generally takes the value from the URL.

How Do I pass a URL if possible to my Test Cases? How do I make sure that the URL is mocked properly? Or does anyone have a better approach/suggestion?

public class BaseController : Controller
{
    protected string Container
    {
        get
        {
            var cont = this.RouteData.Values["container"] as string;
            return cont;
        }
    }
}


public class ItemsController : BaseController
{
    private IItemsServiceRepository _esc;

    public ItemsController(IItemsServiceRepository esc)
    {
        _esc = esc;
    }

    [HttpGet]
    public IActionResult GetItems()
    {
        var items = _esc.GetItems(Container);

        var results = new List<ItemDb>();

        foreach (var item in items)
        {
            results.Add(new ItemDb
            {
                Title = item.Title,
                Type  = "TBD",
                Uri   = "TBD"
            });
        }

        return Ok(results);
    }
}

I would have showed you my unit test but its all a mess now.

Let me know if you need any additional info.

Note: Can anyone tell me how is this a duplicate? So far the link to the one that I was considered a duplicate of didn't help at all. Some explanation is preferred since I'm new to TDD.

HelpWanted
  • 71
  • 1
  • 9
  • 1
    Set up the RouteData, pass that to a ControllerContext and assign that context to your Controller. See duplicate. – CodeCaster May 07 '18 at 08:43
  • @CodeCaster My routing is generally done following this explanation [link](https://benjii.me/2016/08/global-routes-for-asp-net-core-mvc/) Would that affect the approach/answer to the question you specified I was a duplicate of ? – HelpWanted May 07 '18 at 08:50
  • Your edit claiming the duplicate _"didn't help at all"_ should be expanded with what you tried. – CodeCaster May 07 '18 at 09:08

0 Answers0