问题描述
我正在尝试为一个类(在.net Core项目中)编写xunit测试,该类看起来像:
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
}
}`
注意: FoodList
实际上是一个json文件,包含数据,这些数据已在Startup类中加载和配置。
Note: FoodList
is actually a json file, containing data, that is loaded and configured in the Startup class.
如何编写带有适当依赖项注入的xunit测试来测试 IsFoodItemPresentInList
方法?
How can I write an xunit test with appropriate dependency injection to test the IsFoodItemPresentInList
method ?
推荐答案
您可以使用 OptionsWrapper< T>
类伪造您的配置。然后,您可以将此对象传递给要测试的类。这样,您不必使用DI或读取实际配置。
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.
类似这样的事情:
var myConfiguration = new OptionsWrapper<MyConfiguration>(new MyConfiguration
{
SomeConfig = "SomeValue"
});
var yourClass = new YourClass(myConfiguration);
这篇关于实例化IOptions<>在xunit中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!