简体   繁体   中英

Using NSubstitute and Ninject to return a value

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!!!";

        // ? 
    }

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; }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM