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 ?
I have encountered a similar problem (using xUnit), after some struggle, I worked it out.
The answer is so late, but should be helpful for others.
For your Question:
Also, you should copy "appSettings.json" to your project root folder.
You can create an instance of
IOptions<FoodList>
using theOptions.Create
method: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;
And then call it like this;
In a unit test, you typically don't use Dependency Injection, since it's you who controls the creation of the tested object.
To supply a suitable object that implements
IOptions<FoodList>
you can implement a fake class with the desired behavior yourself, or use some mocking framework to configure the instance on the fly, for example Moq.You could use
OptionsWrapper<T>
class to fake your configuration. Then you can pass in this object to your class that you want to test. That way you don't have to use DI or read the real configuration.Something like this: