Automatic testing of ApiController

前端 未结 4 1907
悲哀的现实
悲哀的现实 2021-01-23 06:35

I have an ApiController and would like to test it with unit tests including the routing.

An example:

[RoutePrefix(\"prefix\")]
public class          


        
4条回答
  •  佛祖请我去吃肉
    2021-01-23 07:01

    That is an integration test, not a unit test. If you wanted to automate this you would have to have a tool that would launch/host your web api and then execute requests against it.

    If you wanted to keep it as a unit test though you could validate the attributes on the class and the method and check the values.

    var type = typeof(Controller);
    var attributeRoutePrefix = type.GetCustomAttribute(typeof(RoutePrefixAttribute)) as RoutePrefixAttribute;
    Assert.IsNotNull(attributeRoutePrefix);
    Assert.AreEqual("prefix", attributeRoutePrefix.Prefix);
    
    var methodAttribute = type.GetMethod(nameof(Controller.Add)).GetCustomAttribute(typeof(RouteAttribute)) as RouteAttribute;
    Assert.IsNotNull(methodAttribute);
    Assert.AreEqual("id1", methodAttribute.Template);
    

提交回复
热议问题