Using NSubstitute and Ninject to return a value

て烟熏妆下的殇ゞ 提交于 2019-12-14 02:23:06

问题


In my NinjectDependencyResolver: IDependencyResolver I have a AddBindings() method that for now I want it to return some hard coded values for me until I connect it to DB later.

The class and interface I want to mock and use in that AddBindings() method are like this:

public class Configuration
{
    public string WebSiteNotActiveMessage { get; set; }
    public bool IsWebSiteActive { get; set; }
}

public interface IConfigurationManager
{
    Models.Configuration.Configuration ConfigFileValues { get; }
}

Now I wanted to mock the interface and return a value in my Ninject method so I started writing something like this but got stuck, not sure how I should do it:

  private void AddBindings()
    {
        var config = Substitute.For<IConfigurationManager>();

        config.ConfigFileValues.IsWebSiteActive = true;
        config.ConfigFileValues.WebSiteNotActiveMessage = "Website is not active!!!";

        // ? 
    }

回答1:


In general* NSubstitute will not automatically substitute for members that return classes like Configuration, so you'll need to manually stub it:

var config = Substitute.For<IConfigurationManager>();
config.ConfigFileValues.Returns(new Configuration());
config.ConfigFileValues.IsWebSiteActive = true;
config.ConfigFileValues.WebSiteNotActiveMessage = "Website is not active!!!";

(* the exception being pure virtual classes)

Hope this helps.




回答2:


The main problem regarding your interface is that your only property, ConfigFileValues, has only a getter. It should have also setter, which would initialize it from the class that would implement the interface. In terms of code that I suggest is this:

public interface IConfigurationManager
{
    Models.Configuration.Configuration ConfigFileValues { get; set; }
}


来源:https://stackoverflow.com/questions/36777185/using-nsubstitute-and-ninject-to-return-a-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!