Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8382311
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 9, 20262026-06-09T16:54:12+00:00 2026-06-09T16:54:12+00:00

I’ve set up a Web API project using Ninject, and I’ve used the fix

  • 0

I’ve set up a Web API project using Ninject, and I’ve used the fix detailed here for getting it to work with the latest version of the Web API. Everything is working fine, but I’m now trying to write some tests.

I’m using in-memory hosting to run the project for the tests, as detailed here, as I have a DelegatingHandler that performs authentication and then sets a property on the request message that is used by all the Api Controllers.

So, I’ve got a base class for my tests, and have a SetUp method where I set up the HttpServer and configuration, which I’ve pretty much taken from my working Ninject code:

[SetUp]
public void Setup()
{
    bootstrapper = new Bootstrapper();

    DynamicModuleUtility.RegisterModule(
        typeof(OnePerRequestHttpModule));

    DynamicModuleUtility.RegisterModule(
        typeof(NinjectHttpModule));

    bootstrapper.Initialize(CreateKernel);

    var config = new HttpConfiguration();
    config.Routes.MapHttpRoute("Login",
        "api/auth/token",
        new { controller = "Users", action = "Login" });

    config.IncludeErrorDetailPolicy =
        IncludeErrorDetailPolicy.Always;

    config.DependencyResolver = 
        new NinjectResolver(CreateKernel());

    config.MessageHandlers.Add(
        new AuthenticationHandler(CreateUserManager()));

    Server = new HttpServer(config);
}

This is how I create the MoqMockingKernel:

private static IKernel CreateKernel()
{
    var kernel = new MoqMockingKernel();
    kernel.Bind<Func<IKernel>>()
        .ToMethod(ctx => () => new Bootstrapper().Kernel);
    kernel.Bind<IHttpModule>()
        .To<HttpApplicationInitializationHttpModule>();

    RegisterServices(kernel);

    GlobalConfiguration.Configuration.DependencyResolver = 
        new NinjectResolver(kernel);

    return kernel;
}

And this is how I register the objects to use:

private static void RegisterServices(IKernel kernel)
{
    kernel.Bind<IUserManager>().ToMock();

    kernel.Bind<UsersController>().ToSelf();
}

While I’m not testing the Controller per se, I do want a proper instance of it to be called, which is why I’m binding it ToSelf. I must admit that I am assuming that this is correct. This is an example of a test:

public void UserCannotLogin()
{
    System.Net.Http.HttpClient client = 
        new System.Net.Http.HttpClient(Server);

    string json = string.Format(
        "{{ \"Username\": \"{0}\", \"Password\": \"{1}\" }}", 
        "wrong", "wrong");

    HttpRequestMessage request = 
        CreateRequest(@"api/auth/token", json, HttpMethod.Get);

    Action action = () => client.SendAsync(request);

    using (var response = client.SendAsync(request).Result)
    {
        response.StatusCode.Should()
            .Be(HttpStatusCode.Unauthorized);
    }
}

I’m basically getting a 404 error. When I debug it, it does go to my DelegatingHandler, but it doesn’t go to my controller.

I get the feeling that I’m fundamentally missing a point here, and it may not even be possible to do what I’m trying to do, but if anyone has any suggestions for either how to do this, or a different way to achieve the same thing, I’m all ears.

Update I think that it’s because the default behaviour of the MockingKernel is to provide a Mock unless told otherwise, so it is returning a Mock of IHttpControllerSelector. I’ve set up a couple of default ones now:

kernel.Bind<IHttpControllerSelector>()
    .To<DefaultHttpControllerSelector>();
kernel.Bind<IContentNegotiator>()
    .To<DefaultContentNegotiator>();

It’s still not working, I think because there are no formatters specified. I’ll try that tomorrow and see if that gets me there.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-09T16:54:13+00:00Added an answer on June 9, 2026 at 4:54 pm

    Ok, I think that I was correct when I said that I was fundamentally missing a point here, but I’ll answer this in case it helps someone else avoid the same mistake!

    The Ninject MockingKernel is, I think, primarily about auto-mocking, so where you have a lot of interfaces you don’t care about how they are set up in your test, you can ignore them in your tests and they will be automatically created for you.

    In the case of the Web API, this is most definitely not the case, as you don’t want the controller selector class to be auto mocked, otherwise you won’t end up calling your controllers.

    So, the solution I’ve come up with is to stick with using a standard Ninject Kernel, and then bind your interface to a constant Mock object:

    kernel.Bind<IUserManager>().ToConstant(CreateUserManager());
    
    private IUserManager CreateUserManager()
    {
        Mock<IUserManager> userManager = new Mock<IUserManager>();
    
        // Set up the methods you want mocked
    
        return userManager.Object;
    }
    

    Doing this, I’ve been able to successfully write tests that use an HttpClient to call an in-memory HttpServer that successfully call my DelegatingHandler and then end up at my controllers.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

That's pretty much it. I'm using Nokogiri to scrape a web page what has
I'm making a simple page using Google Maps API 3. My first. One marker
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I used javascript for loading a picture on my website depending on which small
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I am reading a book about Javascript and jQuery and using one of the
I'm using v2.0 of ClassTextile.php, with the following call: $testimonial_text = $textile->TextileRestricted($_POST['testimonial']); ... and
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
We're building an app, our first using Rails 3, and we're having to build
We are using XSLT to translate a RIXML file to XML. Our RIXML contains

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.