Instantiating IOptions<> in xunit

Viewed 5238

I'm trying to write an xunit test for a class (in a .net Core project) that looks something like:

public Class FoodStore:IFoodStore
{
    FoodList foodItems;

    public FoodStore(IOptions<FoodList> foodItems)
    {
        this.foodItems = foodItems;
    }

    public bool IsFoodItemPresentInList(string foodItemId)
    {
        //Logic to search from Food List
    }
}`

Note: FoodList is actually a json file, containing data, that is loaded and configured in the Startup class.

How can I write an xunit test with appropriate dependency injection to test the IsFoodItemPresentInList method ?

5 Answers

You can create an instance of IOptions<FoodList> using the Options.Create method:

var foodListOptions = Options.Create(new FoodList());

As suggested by the other answers, in your test class you can create an options instance just for testing.

You can do it like this;

public class FakeFoodList : IOptions<FoodList>
{
    public FoodList Value
    {
        get
        {
            return new FoodList(); // TODO: Add your settings for test here.
        }
    }
}

And then call it like this;

var foodOptions = new FakeFoodList();
var foodStore = new FoodStore(foodOptions);

var response = foodStore.Act();

Assert.Equal("whatever", response);
Related