GVKun编程网logo

我需要为路由过程编写单元测试吗?(我需要为路由过程编写单元测试吗英语)

14

对于想了解我需要为路由过程编写单元测试吗?的读者,本文将是一篇不可错过的文章,我们将详细介绍我需要为路由过程编写单元测试吗英语,并且为您提供关于APISIX插件如何编写单元测试、asp.net-mvc

对于想了解我需要为路由过程编写单元测试吗?的读者,本文将是一篇不可错过的文章,我们将详细介绍我需要为路由过程编写单元测试吗英语,并且为您提供关于APISIX插件如何编写单元测试、asp.net-mvc – 我应该为控制器或服务层或两者编写单元测试吗?、c# – 我们可以在.aspx.cs页面中编写单元测试方法吗?、Fakes编写单元测试的有价值信息。

本文目录一览:

我需要为路由过程编写单元测试吗?(我需要为路由过程编写单元测试吗英语)

我需要为路由过程编写单元测试吗?(我需要为路由过程编写单元测试吗英语)

如何解决我需要为路由过程编写单元测试吗??

我目前正在使用 Express 构建网络应用程序。我想为我的网络应用编写单元测试。

我是否需要为每个路由进程编写单元测试? 如果我需要为路由进程编写单元测试,请告诉我为什么需要编写它。

解决方法

这取决于您对测试覆盖率或高覆盖率要求(>80% 或其他)的信心水平。 通常路由的业务逻辑是调用适当的控制器,因此您的测试可能仅限于模拟控制器并检查(断言)控制器的正确方法被调用。

APISIX插件如何编写单元测试

APISIX插件如何编写单元测试

参考文档:

  • Run Test
  • ❗️❗️❗️Test Nginx 语法详细说明

example.lua

local core = require("apisix.core")
local pairs = pairs
local type = type
local ngx = ngx
local buffers = {}
local schema = {
    type = "object",
    properties = {
        message = {
            description = "需要打印的日志",
            type = "string"
        }
    },
    required = { "message" },
    minProperties = 1,
}

local plugin_name = "example"

local _M = {
    version = 0.1,
    priority = 412,
    name = plugin_name,
    schema = schema,
}

function _M.check_schema(conf)
    local ok, err = core.schema.check(schema, conf)
    if not ok then
        return false, err
    end
    core.log.info("xxxxxxxx: ", "gjx")
    return true
end

function _M.log(conf, ctx)
    buffers.message = conf.message
    core.log.debug("metadata:",core.json.encode(buffers,true))
end

return _M

Example.t

use t::APISIX ''no_plan'';

repeat_each(1); -- 重复次数
no_long_string(); -- 默认地,失败的字符串匹配测试将会使用 Test::LongString 模块产生一个错误信息,在 run_tests 之前调用这个函数将会关闭它
no_root_location();
no_shuffle(); -- 在no_shuffle()调用的情况下,测试块的运行顺序与它们在测试文件中出现的顺序完全一致
log_level(''debug''); -- 日志级别
run_tests; -- 这个放在最后

__DATA__

=== TEST 1: sanity  -- 用例名称
--- config   -- 用于配置Nginx conf 信息
    location /t {
        content_by_lua_block {
            local plugin = require("apisix.plugins.example")
             local ctx ={
                headers={
                }
            }
            local ok, err = plugin.check_schema({message="gejiax"})
            if not ok then
                ngx.say(err)
            end
            plugin.log({message="gejiax"},ctx)
            ngx.say("done")  -- 打印结果
        }
    }
--- request  -- 调用请求,校验结果
GET /t
--- more_headers -- 头部信息
Authorization: Bearer eyJhbGc
--- response_headers  -- 响应返回头部信息
in: out
--- error_code: 401 -- 状态码
--- response_body  -- 请求结果
done
--- no_error_log  -- 表示会对 nginx 的 error.log 检查,必须没有 EORROR 级别的记录
[error]
--- response_body_like eval  --返回值正则表达式校验
qr/"Access Denied"/
--- error_log eval   --错误日志正则表达式
qr/conf_version: \d+#1,/

content_by_lua_block 说明

=== TEST 12: Add https endpoint with ssl_verify false
--- config
    location /t {
        content_by_lua_block {
            local t = require("lib.test_admin").test  -- 调用apisix接口的实现,就是如何去调用API接口的示例
            local code, body = t(''/apisix/admin/routes/1'',
                 ngx.HTTP_PUT,
                 [[{
                        "plugins": {
                            "authz-keycloak": {
                                "token_endpoint": "https://127.0.0.1:8443/auth/realms/University/protocol/openid-connect/token",
                                "permissions": ["course_resource#delete"],
                                "client_id": "course_management",
                                "grant_type": "urn:ietf:params:oauth:grant-type:uma-ticket",
                                "timeout": 3000,
                                "ssl_verify": false
                            }
                        },
                        "upstream": {
                            "nodes": {
                                "127.0.0.1:1982": 1
                            },
                            "type": "roundrobin"
                        },
                        "uri": "/hello1"
                }]],
                [[{
                    "node": {
                        "value": {
                            "plugins": {
                                "authz-keycloak": {
                                    "token_endpoint": "https://127.0.0.1:8443/auth/realms/University/protocol/openid-connect/token",
                                    "permissions": ["course_resource#delete"],
                                    "client_id": "course_management",
                                    "grant_type": "urn:ietf:params:oauth:grant-type:uma-ticket",
                                    "timeout": 3000,
                                    "ssl_verify": false
                                }
                            },
                            "upstream": {
                                "nodes": {
                                    "127.0.0.1:1982": 1
                                },
                                "type": "roundrobin"
                            },
                            "uri": "/hello1"
                        },
                        "key": "/apisix/routes/1"
                    },
                    "action": "set"
                }]]
                )

            if code >= 300 then
                ngx.status = code
            end
            ngx.say(body)
        }
    }
--- request
GET /t
--- response_body
passed
--- no_error_log
[error]

HTTP 请求

location /t {
        content_by_lua_block {
            local json_decode = require("toolkit.json").decode  -- json 工具类
            local http = require "resty.http"
            local httpc = http.new()
            local uri = "http://127.0.0.1:8090/auth/realms/University/protocol/openid-connect/token"
            local res, err = httpc:request_uri(uri, {
                    method = "POST",
                    body = "grant_type=password&client_id=course_management&client_secret=d1ec69e9-55d2-4109-a3ea-befa071579d5&username=teacher@gmail.com&password=123456",
                    headers = {
                        ["Content-Type"] = "application/x-www-form-urlencoded"
                    }
                })

            if res.status == 200 then
                local body = json_decode(res.body)
                local accessToken = body["access_token"]


                uri = "http://127.0.0.1:" .. ngx.var.server_port .. "/hello1"
                local res, err = httpc:request_uri(uri, {
                    method = "GET",
                    headers = {
                        ["Authorization"] = "Bearer " .. accessToken,
                    }
                 })

                if res.status == 200 then
                    ngx.say(true)
                else
                    ngx.say(false)
                end
            else
                ngx.say(false)
            end
        }
    }

多个location

=== TEST 6: first request timeout
--- config
    location = /aggregate {
        content_by_lua_block {
            local core = require("apisix.core")
            local t = require("lib.test_admin").test
            local code, body = t(''/apisix/batch-requests'',
                ngx.HTTP_POST,
                [=[{
                    "timeout": 100,
                    "pipeline":[
                    {
                        "path": "/b",
                        "headers": {
                            "Header1": "hello",
                            "Header2": "world"
                        }
                    },{
                        "path": "/c",
                        "method": "PUT"
                    },{
                        "path": "/d"
                    }]
                }]=],
                [=[[
                {
                    "status": 504,
                    "reason": "upstream timeout"
                }
                ]]=]
                )

            ngx.status = code
            ngx.say(body)
        }
    }

    location = /b {
        content_by_lua_block {
            ngx.sleep(1)
            ngx.status = 200
        }
    }
    location = /c {
        content_by_lua_block {
            ngx.status = 201
        }
    }
    location = /d {
        content_by_lua_block {
            ngx.status = 202
        }
    }
--- request
GET /aggregate
--- response_body
passed
--- error_log
timeout

asp.net-mvc – 我应该为控制器或服务层或两者编写单元测试吗?

asp.net-mvc – 我应该为控制器或服务层或两者编写单元测试吗?

我正在学习并尝试使用单元测试来完成我的项目.但是当我尝试使用单元测试编写演示时,我看到控制器的单元测试与服务层相同.下面是我为控制器和服务层编写的单元测试代码

控制器测试:

private Mock<ICountryService> _countryServiceMock;
  CountryController objController;
  List<Country> listCountry;

  [Testinitialize]
  public void Initialize()
  {

      _countryServiceMock = new Mock<ICountryService>();
      objController = new CountryController(_countryServiceMock.Object);
      listCountry = new List<Country>() {
       new Country() { Id = 1,Name = "US" },new Country() { Id = 2,Name = "India" },new Country() { Id = 3,Name = "Russia" }
      };
  }

  [TestMethod]
  public void Country_Get_All()
  {
      //Arrange
      _countryServiceMock.Setup(x => x.GetAll()).Returns(listCountry);

      //Act
      var result = ((objController.Index() as ViewResult).Model) as List<Country>;

      //Assert
      Assert.AreEqual(result.Count,3);
      Assert.AreEqual("US",result[0].Name);
      Assert.AreEqual("India",result[1].Name);
      Assert.AreEqual("Russia",result[2].Name);

  }

服务测试:

private Mock<ICountryRepository> _mockRepository;
  private ICountryService _service;
  Mock<IUnitOfWork> _mockUnitWork;
  List<Country> listCountry;

  [Testinitialize]
  public void Initialize()
  {
      _mockRepository = new Mock<ICountryRepository>();
      _mockUnitWork = new Mock<IUnitOfWork>();
      _service = new CountryService(_mockUnitWork.Object,_mockRepository.Object);
      listCountry = new List<Country>() {
       new Country() { Id = 1,Name = "Russia" }
      };
  }

  [TestMethod]
  public void Country_Get_All()
  {
      //Arrange
      _mockRepository.Setup(x => x.GetAll()).Returns(listCountry);

      //Act
      List<Country> results = _service.GetAll() as List<Country>;

      //Assert
      Assert.IsNotNull(results);
      Assert.AreEqual(3,results.Count);
  }

解决方法

在控制器级别,我倾向于编写端到端测试.没有嘲笑,没有假货,只有真实的东西.

原因是在上面的测试中,您的单元测试与控制器操作的实现细节相关联.假设您不再使用存储库或工作单元,您的测试将不再编译.在这个级别,您应该关注测试行为,而不是实现.

我单元测试隔离域模型,其余的集成测试.

c# – 我们可以在.aspx.cs页面中编写单元测试方法吗?

c# – 我们可以在.aspx.cs页面中编写单元测试方法吗?

我们可以在.aspx.cs页面中编写测试方法吗?
如果是,那怎么样?
我需要为Page_Load方法中的代码编写测试方法.
请建议是否有任何解决方案.

解决方法

可能你可以,但是如果你将Page_Load方法的逻辑提取到模型类中然后单独测试它会更加清晰.

为什么?

>在其他页面中重用该方法的逻辑
>更好地分离模型和演示文稿
>更容易测试的清洁代码

样品:

// Home.aspx.cs
Page_Load()
{
    //Lots of code here
}


// or else Home.aspx.cs
Page_Load()
{
    Foo f = new Foo();
    var result = f.DoThings();
}

//Unit test
Page_Load_FoodoesThings()
{
    //Arrange
    Foo f = new Foo();
    var expected = ...;

    //Act
    var actual = f.DoThings();

    //Assert
    Assert.AreEqual(expected,actual)
}

Fakes编写单元测试

Fakes编写单元测试

在单元测试的程序集中,找到需要测试的程序集引用,右键添加Fakes程序集,即可。

一、底层类和接口的

    public interface ICity
    {
        int GetCityDal();
    }

    public class City : ICity
    {
        public int GetCityDal()
        {
            return 85;
        }
    }

二、调用City类的类,即被测试类

    public class HomeController : Controller
    {
        ICity _city = null;
        public HomeController()
        {
        }

        public HomeController(ICity city)
        {
            _city = city;
        }

        public ActionResult Index()
        {
            return Content("0");
        }

        public int GetCity()
        {
            City c = new City();
            int ac = c.GetCityDal();
            return ac + 1;
        }

        public int GetCityIOC()
        {
            int ac = _city.GetCityDal();
            return ac + 1;
        }

        public static bool IsDouble()
        {
            if (DateTime.Now.Day % 2 == 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }

三、编写的单元测试类

    [TestClass]
    public class HomeControllerTest
    {
        [TestMethod]
        public void IndexTest()
        {
            HomeController hc = new HomeController();
            ContentResult vr = hc.Index() as ContentResult;
            Assert.AreEqual(vr.Content, "0");

        }

        //强依赖性
        [TestMethod]
        public void GetCityTest()
        {
            //尽量不要出现此单元测试
            int r = 0;
            using (ShimsContext.Create())
            {
                ShimCity.AllInstances.GetCityDal = (@this) =>
                {
                    return 10;
                };
                HomeController hc = new HomeController();
                r = hc.GetCity();
            }
            Assert.AreEqual(r, 11);
        }

        //弱依赖性
        [TestMethod]
        public void GetCityIOCTest()
        {
            ICity city = new StubICity()
            {
                GetCityDal = () =>
                {
                    return 20;
                }
            };
            HomeController hc = new HomeController(city);
            int r = hc.GetCityIOC();

            Assert.AreEqual(r, 21);
        }

        //静态类测试
        [TestMethod]
        public void IsDoubleTest()
        {
            bool temp = false;
            using (ShimsContext.Create())
            {
                ShimDateTime.NowGet = () => new DateTime(2017, 3, 28);
                temp = HomeController.IsDouble();
            }
            Assert.IsTrue(temp);
        }
    }

 

 

今天的关于我需要为路由过程编写单元测试吗?我需要为路由过程编写单元测试吗英语的分享已经结束,谢谢您的关注,如果想了解更多关于APISIX插件如何编写单元测试、asp.net-mvc – 我应该为控制器或服务层或两者编写单元测试吗?、c# – 我们可以在.aspx.cs页面中编写单元测试方法吗?、Fakes编写单元测试的相关知识,请在本站进行查询。

本文标签: