简体   繁体   中英

Routing in Web API is not working in my integration tests

Here's my solution structure:

  • Project A (Class Library) : Main Functionality API Controllers
  • Project B (Class Library) : Additional Functionality API Controllers
  • Project C (ASP.NET Web) : Web API Host (just contains Global.asax and configuration code)
  • Project D (MS Test) : Web API Integration tests

In my Project D I have test cases for all controllers in Project A and they all run fine. However, for the integration test case that I wrote for a controller in Project B I keep getting the error 404: No type was found that matches the controller named 'notifications'.

What I tried:

  • I initially had attribute routing and thought there might have been a problem, with attribute routing, and removed the attributes and changed my URL to match the default route, and I still have the same problem.
  • I thought the assembly wasn't being loaded as there are no direct usage, and hence I forced the type to be loaded using a call to typeof(NotificationsController) and ran an assertion on the return value.
  • I tested this with a regular browser and I am able to get the result for attribute routing as well.
  • I checked NotificationsController is in fact deriving from ApiController (through another base class of course, but that is the same base class for all my API controllers)

My test code initialization is like below:

var config = new HttpConfiguration();
config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;

WebApp.Start(config);

HttpServer = new HttpServer(config);

My Global.asax code in Project C is like below:

GlobalConfiguration.Configure(WebApp.Start);

In my WebApp.Start method, I do have a call to config.EnsureInitialized() . I am not sure if it is of any consequence, but I am using Unity DI and have ensured that Unity configuration is also happening in the flow.

What might I be missing at this point? How do I proceed to debug this further. Any help on this is greatly appreciated.

Finally, I think, I found the root cause!

My test code initialization is placed in a static method with [AssemblyInitialize] attribute on it. I have now removed it and changed it to a singleton pattern and letting the initialization occur on the first use. And I am ensuring my NotificationsController type is loaded before this first use. And this solved my problem!

This is loading my controller consistently so far.

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