欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

ASP.NET Core对Controller进行单元测试的完整步骤

程序员文章站 2022-03-08 08:32:43
前言单元测试对我们的代码质量非常重要。很多同学都会对业务逻辑或者工具方法写测试用例,但是往往忽略了对controller层写单元测试。我所在的公司没见过一个对controller写过测试的。今天来演示...

前言

单元测试对我们的代码质量非常重要。很多同学都会对业务逻辑或者工具方法写测试用例,但是往往忽略了对controller层写单元测试。我所在的公司没见过一个对controller写过测试的。今天来演示下如果对controller进行单元测试。以下内容默认您对单元测试有所了解,比如如何mock一个接口。在这里多叨叨一句,面向接口的好处,除了能够快速的替换实现类(其实大部分接口不会有多个实现),最大的好处就是可以进行mock,可以进行单元测试。

测试action

下面的action非常简单,非常常见的一种代码。根据用户id去获取用户信息然后展示出来。下面看看如何对这个action进行测试。

  public class usercontroller : controller
  {
    private readonly iuserservice _userservice;
    public usercontroller(iuserservice userservice)
    {
      _userservice = userservice;
    }

    public iactionresult userinfo(string userid)
    {
      if (string.isnullorempty(userid))
      {
        throw new argumentnullexception(nameof(userid));
      }

      var user = _userservice.get(userid);
      return view(user);
    }
   
  }

测试代码:

 [testmethod()]
    public void userinfotest()
    {

      var userservice = new mock<iuserservice>();
      userservice.setup(s => s.get(it.isany<string>())).returns(new user());

      var ctrl = new usercontroller(userservice.object);
      //对空参数进行assert
      assert.throwsexception<argumentnullexception>(() => {
        var result = ctrl.userinfo(null);
      });
      //对空参数进行assert
      assert.throwsexception<argumentnullexception>(() => {
        var result = ctrl.userinfo("");
      });

      var result = ctrl.userinfo("1");
      assert.isnotnull(result);
      assert.isinstanceoftype(result, typeof(viewresult));
    }

我们对一个action进行测试主要的思路就是模拟各种入参,使测试代码能够到达所有的分支,并且assert输出是否为空,是否为指定的类型等。

对viewmodel进行测试

我们编写action的时候还会涉及viewmodel给视图传递数据,这部分也需要进行测试。修改测试用例,加入对viewmodel的测试代码:

 [testmethod()]
    public void userinfotest()
    {
      var userservice = new mock<iuserservice>();
      userservice.setup(s => s.get(it.isany<string>())).returns(new user()
      {
        id = "x"
      }) ;

      var ctrl = new usercontroller(userservice.object);
      assert.throwsexception<argumentnullexception>(() => {
        var result = ctrl.userinfo(null);
      });
      assert.throwsexception<argumentnullexception>(() => {
        var result = ctrl.userinfo("");
      });

      var result = ctrl.userinfo("1");
      assert.isnotnull(result);
      assert.isinstanceoftype(result, typeof(viewresult));
      //对viewmodel进行assert
      var vr = result as viewresult;
      assert.isnotnull(vr.model);
      assert.isinstanceoftype(vr.model, typeof(user));
      var user = vr.model as user;
      assert.areequal("x", user.id);
    }

对viewdata进行测试

我们编写action的时候还会涉及viewdata给视图传递数据,这部分同样需要测试。修改action代码,对viewdata进行赋值:

  public iactionresult userinfo(string userid)
    {
      if (string.isnullorempty(userid))
      {
        throw new argumentnullexception(nameof(userid));
      }

      var user = _userservice.get(userid);

      viewdata["title"] = "user_info";

      return view(user);
    }
   

修改测试用例,加入对viewdata的测试代码:

  [testmethod()]
    public void userinfotest()
    {
      var userservice = new mock<iuserservice>();
      userservice.setup(s => s.get(it.isany<string>())).returns(new user()
      {
        id = "x"
      }) ;

      var ctrl = new usercontroller(userservice.object);
      assert.throwsexception<argumentnullexception>(() => {
        var result = ctrl.userinfo(null);
      });
      assert.throwsexception<argumentnullexception>(() => {
        var result = ctrl.userinfo("");
      });

      var result = ctrl.userinfo("1");
      assert.isnotnull(result);
      assert.isinstanceoftype(result, typeof(viewresult));

      var vr = result as viewresult;
      assert.isnotnull(vr.model);
      assert.isinstanceoftype(vr.model, typeof(user));
      var user = vr.model as user;
      assert.areequal("x", user.id);
      //对viewdata进行assert
      assert.istrue(vr.viewdata.containskey("title"));
      var title = vr.viewdata["title"];
      assert.areequal("user_info", title);
    }

对viewbag进行测试

因为viewbag事实上是viewdata的dynamic类型的包装,所以action代码不用改,可以直接对viewbag进行测试:

   [testmethod()]
    public void userinfotest()
    {
      var userservice = new mock<iuserservice>();
      userservice.setup(s => s.get(it.isany<string>())).returns(new user()
      {
        id = "x"
      }) ;

      var ctrl = new usercontroller(userservice.object);
      assert.throwsexception<argumentnullexception>(() => {
        var result = ctrl.userinfo(null);
      });
      assert.throwsexception<argumentnullexception>(() => {
        var result = ctrl.userinfo("");
      });

      var result = ctrl.userinfo("1");
      assert.isnotnull(result);
      assert.isinstanceoftype(result, typeof(viewresult));

      var vr = result as viewresult;
      assert.isnotnull(vr.model);
      assert.isinstanceoftype(vr.model, typeof(user));
      var user = vr.model as user;
      assert.areequal("x", user.id);

      assert.istrue(vr.viewdata.containskey("title"));
      var title = vr.viewdata["title"];
      assert.areequal("user_info", title);
      //对viewbag进行assert
      string title1 = ctrl.viewbag.title;
      assert.areequal("user_info", title1);
    }

设置httpcontext

我们编写action的时候很多时候需要调用基类里的httpcontext,比如获取request对象,获取path,获取headers等等,所以有的时候需要自己实例化httpcontext以进行测试。

  var ctrl = new accountcontroller();
  ctrl.controllercontext = new controllercontext();
  ctrl.controllercontext.httpcontext = new defaulthttpcontext();

对httpcontext.signinasync进行mock

我们使用asp.net core框架进行登录认证的时候,往往使用httpcontext.signinasync进行认证授权,所以单元测试的时候也需要进行mock。下面是一个典型的登录action,对密码进行认证后调用signinasync在客户端生成登录凭证,否则跳到登录失败页面。

  public async task<iactionresult> login(string password)
    {
      if (password == "123")
      {
        var claims = new list<claim>
        {
         new claim("username","x")
        };
        var authproperties = new authenticationproperties
        {
        };
        var claimsidentity = new claimsidentity(
         claims, cookieauthenticationdefaults.authenticationscheme);
        await httpcontext.signinasync(
          cookieauthenticationdefaults.authenticationscheme,
          new claimsprincipal(claimsidentity),
          authproperties);
        return redirect("login_success");
      }

      return redirect("login_fail");
    }

httpcontext.signinasync其实个时扩展方法,signinasync其实最终是调用了iauthenticationservice里的signinasync方法。所以我们需要mock的就是iauthenticationservice接口,否者代码走到httpcontext.signinasync会提示找不到iauthenticationservice的service。而iauthenticationservice本身是通过iserviceprovider注入到程序里的,所以同时需要mock接口iserviceprovider。

  [testmethod()]
    public async task logintest()
    {
      var ctrl = new accountcontroller();

      var authenticationservice = new mock<iauthenticationservice>();
      var sp = new mock<iserviceprovider>();
      sp.setup(s => s.getservice(typeof(iauthenticationservice)))
        .returns(() => {
          return authenticationservice.object;
        });
      ctrl.controllercontext = new controllercontext();
      ctrl.controllercontext.httpcontext = new defaulthttpcontext();
      ctrl.controllercontext.httpcontext.requestservices = sp.object;

      var result = await ctrl.login("123");
      assert.isnotnull(result);
      assert.isinstanceoftype(result, typeof(redirectresult));
      var rr = result as redirectresult;
      assert.areequal("login_success", rr.url);

      result = await ctrl.login("1");
      assert.isnotnull(result);
      assert.isinstanceoftype(result, typeof(redirectresult));
      rr = result as redirectresult;
      assert.areequal("login_fail", rr.url);
    }

对httpcontext.authenticateasync进行mock

httpcontext.authenticateasync同样比较常用。这个扩展方法同样是在iauthenticationservice里,所以测试代码跟上面的signinasync类似,只是需要对authenticateasync继续mock返回值success or fail。

   public async task<iactionresult> login()
    {
      if ((await httpcontext.authenticateasync()).succeeded)
      {
        return redirect("/home");
      }

      return redirect("/login");
    }

测试用例:

    [testmethod()]
    public async task logintest1()
    {
      var authenticationservice = new mock<iauthenticationservice>();
      //设置authenticateasync为success
      authenticationservice.setup(s => s.authenticateasync(it.isany<httpcontext>(), it.isany<string>()))
        .returnsasync(authenticateresult.success(new authenticationticket(new system.security.claims.claimsprincipal(), "")));
      var sp = new mock<iserviceprovider>();
      sp.setup(s => s.getservice(typeof(iauthenticationservice)))
        .returns(() => {
          return authenticationservice.object;
        });

      var ctrl = new accountcontroller();
      ctrl.controllercontext = new controllercontext();
      ctrl.controllercontext.httpcontext = new defaulthttpcontext();
      ctrl.controllercontext.httpcontext.requestservices = sp.object;

      var act = await ctrl.login();
      assert.isnotnull(act);
      assert.isinstanceoftype(act, typeof(redirectresult));
      var rd = act as redirectresult;
      assert.areequal("/home", rd.url);
      //设置authenticateasync为fail
      authenticationservice.setup(s => s.authenticateasync(it.isany<httpcontext>(), it.isany<string>()))
        .returnsasync(authenticateresult.fail(""));

      act = await ctrl.login();
      assert.isnotnull(act);
      assert.isinstanceoftype(act, typeof(redirectresult));
      rd = act as redirectresult;
      assert.areequal("/login", rd.url);

    }

filter进行测试

我们写controller的时候往往需要配合很多filter使用,所以filter的测试也很重要。下面演示下如何对fitler进行测试。

  public class myfilter: actionfilterattribute
  {
    public override void onactionexecuting(actionexecutingcontext context)
    {
      if (context.httpcontext.request.path.value.contains("/abc/"))
      {
        context.result = new contentresult() {
          content = "拒绝访问"
        };
      }

      base.onactionexecuting(context);
    }
  }

对filter的测试最主要的是模拟actionexecutingcontext参数,以及其中的httpcontext等,然后对预期进行assert。

    [testmethod()]
    public void onactionexecutingtest()
    {
      var filter = new myfilter();
      var actcontext = new actioncontext(new defaulthttpcontext(),new routedata(), new actiondescriptor());
      actcontext.httpcontext.request.path = "/abc/123";
      var listfilters = new list<ifiltermetadata>();
      var argdict = new dictionary<string, object>();
      var actexcontext = new actionexecutingcontext(
        actcontext ,
        listfilters ,
        argdict ,
        new accountcontroller()
        );
       filter.onactionexecuting(actexcontext);

      assert.isnotnull(actexcontext.result);
      assert.isinstanceoftype(actexcontext.result, typeof(contentresult));
      var cr = actexcontext.result as contentresult;
      assert.areequal("拒绝访问", cr.content);

      actcontext = new actioncontext(new defaulthttpcontext(), new routedata(), new actiondescriptor());
      actcontext.httpcontext.request.path = "/1/123";
      listfilters = new list<ifiltermetadata>();
      argdict = new dictionary<string, object>();
      actexcontext = new actionexecutingcontext(
        actcontext,
        listfilters,
        argdict,
        new accountcontroller()
        );
      filter.onactionexecuting(actexcontext);
      assert.isnull(actexcontext.result);
    }

总结

到此这篇关于asp.net core对controller进行单元测试的文章就介绍到这了,更多相关asp.net core对controller单元测试内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!