.NET Core Unit Testing - Mock IOptions

前端 未结 8 896
难免孤独
难免孤独 2020-12-12 17:55

I feel like I\'m missing something really obvious here. I have classes that require injecting of options using the .NET Core IOptions pattern(?). When I unit te

8条回答
  •  臣服心动
    2020-12-12 18:22

    If you intent to use the Mocking Framework as indicated by @TSeng in the comment, you need to add the following dependency in your project.json file.

       "Moq": "4.6.38-alpha",
    

    Once the dependency is restored, using the MOQ framework is as simple as creating an instance of the SampleOptions class and then as mentioned assign it to the Value.

    Here is a code outline how it would look.

    SampleOptions app = new SampleOptions(){Title="New Website Title Mocked"}; // Sample property
    // Make sure you include using Moq;
    var mock = new Mock>();
    // We need to set the Value of IOptions to be the SampleOptions Class
    mock.Setup(ap => ap.Value).Returns(app);
    

    Once the mock is setup, you can now pass the mock object to the contructor as

    SampleRepo sr = new SampleRepo(mock.Object);   
    

    HTH.

    FYI I have a git repository that outlines these 2 approaches on Github/patvin80

提交回复
热议问题