使用NUnit的执行与ASP.NET的WebAPI控制器集成测试控制器、测试、ASP、NUnit

2023-09-02 23:57:28 作者:睡美人的小仙女

我使用NUnit进行了ASP.NET的WebAPI控制器集成测试是试图建立一个测试。我发现一对夫妇的文章讨论在内存使用的HttpServer出现由不需要Web服务器托管的一切事情简单化托管。

的ASP.NET Web API:内存托管 ASP.NET网络API集成测试与内存托管

问题是我得到的唯一回应是404,没有找到。

控制器工作时,通过浏览器或提琴手手动测试。路由定义是从工作现场复制。该API项目由测试项目中引用的DLL是越来越复制到同一文件夹中的测试。

在此先感谢。

下面是测试类

  [的TestFixture]
公共类InMemoryTests
{
    私人HttpServer的服务器;
    私人字符串UrlBase =HTTP://some.server/;

    [TestFixtureSetUp]
    公共无效设置()
    {

        无功配置=新HttpConfiguration();
        config.Routes.MapHttpRoute(名称:默认,routeTemplate:API / {控制器} / {行动} / {ID},默认值:新{n = RouteParameter.Optional});
        config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;

        服务器=新的HttpServer(配置);
    }

    [测试]
    公共无效GetOrderStatus()
    {
        VAR的客户=新的HttpClient(服务器);
        VAR请求=的createRequest(API /订单/ GetOrderStatus公司code = 001安培; ORDERNUMBER = 1234,应用/ JSON,HttpMethod.Get);

        使用(Htt的presponseMessage响应= client.SendAsync(要求)。结果)
        {
            Assert.IsNotNull(响应);
            Assert.AreEqual(的HTTPStatus code.OK,response.Status code);
            Assert.NotNull(response.Content);
        }
    }

    私人的Htt prequestMessage的createRequest(字符串URL,串mthv,HttpMethod法)
    {
        VAR请求=新的Htt prequestMessage();

        request.RequestUri =新的URI(UrlBase +网址);
        request.Headers.Accept.Add(新MediaTypeWithQualityHeaderValue(mthv));
        request.Method =方法;

        返回请求;
    }

    私人的Htt prequestMessage的createRequest< T>(URL字符串,字符串mthv,HttpMethod方法,T含量,MediaTypeFormatter格式化)其中T:类
    {
        HTT prequestMessage请求=的createRequest(URL,mthv,法);
        request.Content =新ObjectContent< T>(内容,格式);

        返回请求;
    }

    公共无效的Dispose()
    {
        如果(服务器!= NULL)
        {
            Server.Dispose();
        }
    }
}
 

解决方案

我看到这个问题也似乎消失,当我提出我的测试类在同一个组件,我的控制器;一般不实际的测试中,我知道了。

Webapi报错 找到了与该请求匹配的多个操作

在有点挖它似乎有只发生在自主机时调用code不共享相同的组件,控制器,因为它并没有成功地加载所需的组件中的错误。

要确认这是你们的问题/解决办法临时添加此作为测试的第一行: -

  MyType类型= ty​​peof运算(myControllerType);
 

在更多信息: http://forums.asp.net/t/1772734.aspx/1

I'm trying to setup a test using NUnit to perform some integration testing of ASP.NET WebApi controllers. I've found a couple articles discussing In-Memory hosting using HttpServer that appears to simplify things by not needing a web server hosting everything.

ASP.NET Web API: in-memory hosting ASP.NET Web API integration testing with in-memory hosting

The problem is the only response I ever get is 404-Not Found.

The controller are working when manually tested via a browser or Fiddler. The route definition was copied from the working site. The api project is referenced by the test project and the dll is getting copied to the same folder as the tests.

Thanks in advance.

Here's the test class

[TestFixture]
public class InMemoryTests
{
    private HttpServer Server;
    private string UrlBase = "http://some.server/";

    [TestFixtureSetUp]
    public void Setup()
    {

        var config = new HttpConfiguration();
        config.Routes.MapHttpRoute(name: "Default", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional });
        config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;

        Server = new HttpServer(config);
    }

    [Test]
    public void GetOrderStatus()
    {
        var client = new HttpClient(Server);
        var request = createRequest("api/Orders/GetOrderStatus?companyCode=001&orderNumber=1234", "application/json", HttpMethod.Get);

        using (HttpResponseMessage response = client.SendAsync(request).Result)
        {
            Assert.IsNotNull(response);
            Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
            Assert.NotNull(response.Content);
        }
    }

    private HttpRequestMessage createRequest(string url, string mthv, HttpMethod method)
    {
        var request = new HttpRequestMessage();

        request.RequestUri = new Uri(UrlBase + url);
        request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(mthv));
        request.Method = method;

        return request;
    }

    private HttpRequestMessage createRequest<T>(string url, string mthv, HttpMethod method, T content, MediaTypeFormatter formatter) where T : class
    {
        HttpRequestMessage request = createRequest(url, mthv, method);
        request.Content = new ObjectContent<T>(content, formatter);

        return request;
    }

    public void Dispose()
    {
        if (Server != null)
        {
            Server.Dispose();
        }
    }
}

解决方案

I was seeing this problem also, seemed to go away when I moved my test class into the same assembly as my controller; generally not practical for testing I know.

After a bit of digging it appears there's a bug that only occurs with self host when the calling code doesn't share the same assembly as the controller as it hasn't managed to load the required assemblies.

To confirm this is your problem / temporarily workaround add this as the first line of your test: -

Type myType = typeof(myControllerType);

More info at : http://forums.asp.net/t/1772734.aspx/1

 
精彩推荐
图片推荐