minitest - 模拟 - 期望关键字参数
minitest - mock - expect keyword arguments
当我想验证 mock 是否发送了预期的参数时,我可以这样做
@mock.expect(:fnc, nil, ["a, "b"])
但是,如果 class 我想模拟成这样
class Foo
def fnc a:, b:
end
end
我如何模拟它并验证作为 a:
、b:
传递的值?
基于@nus comment,
class FooTest
def test_fnc_arguments
Foo.new.fnc a: "a", b: "b"
# assert true # optional
end
end
以下是我公司代码库中的真实示例:
mailer = MiniTest::Mock.new
mailer.expect :deliver, 123 do |template_name:, data:, to:, subject:|
true
end
mailer.deliver template_name: "xxx", data: {}, to: [], subject: "yyy"
如果您还想验证参数的类型:
mailer.expect :deliver, 123 do |template_name:, data:, to:, subject:|
template_name.is_a?(String) &&
data.is_a?(Hash) &&
to.is_a?(Array) &&
subject.is_a?(String) &&
end
更新 2022-05-22
如果您将此策略与 Ruby v3.
一起使用,您将获得 ArgumentError
我已经在这里提交了一个 PR 来解决这个问题:
https://github.com/minitest/minitest/pull/908
如果您希望在 Ruby v3 中使用此功能,请发表评论以引起项目所有者的注意。
require 'minitest/autorun'
class APIClient
def call; end
end
class APIClientTest < Minitest::Test
def test_keyword_aguments_expection
api_client = Minitest::Mock.new
api_client.expect(:call, true, [{ endpoint_url: 'https://api.test', secret_key: 'test' }])
api_client.call(endpoint_url: 'https://api.test', secret_key: 'test')
api_client.verify
end
end
# Running:
.
Finished in 0.000726s, 1377.5945 runs/s, 0.0000 assertions/s.
1 runs, 0 assertions, 0 failures, 0 errors, 0 skips
[Finished in 0.7s]
当我想验证 mock 是否发送了预期的参数时,我可以这样做
@mock.expect(:fnc, nil, ["a, "b"])
但是,如果 class 我想模拟成这样
class Foo
def fnc a:, b:
end
end
我如何模拟它并验证作为 a:
、b:
传递的值?
基于@nus comment,
class FooTest
def test_fnc_arguments
Foo.new.fnc a: "a", b: "b"
# assert true # optional
end
end
以下是我公司代码库中的真实示例:
mailer = MiniTest::Mock.new
mailer.expect :deliver, 123 do |template_name:, data:, to:, subject:|
true
end
mailer.deliver template_name: "xxx", data: {}, to: [], subject: "yyy"
如果您还想验证参数的类型:
mailer.expect :deliver, 123 do |template_name:, data:, to:, subject:|
template_name.is_a?(String) &&
data.is_a?(Hash) &&
to.is_a?(Array) &&
subject.is_a?(String) &&
end
更新 2022-05-22
如果您将此策略与 Ruby v3.
一起使用,您将获得ArgumentError
我已经在这里提交了一个 PR 来解决这个问题:
https://github.com/minitest/minitest/pull/908
如果您希望在 Ruby v3 中使用此功能,请发表评论以引起项目所有者的注意。
require 'minitest/autorun'
class APIClient
def call; end
end
class APIClientTest < Minitest::Test
def test_keyword_aguments_expection
api_client = Minitest::Mock.new
api_client.expect(:call, true, [{ endpoint_url: 'https://api.test', secret_key: 'test' }])
api_client.call(endpoint_url: 'https://api.test', secret_key: 'test')
api_client.verify
end
end
# Running:
.
Finished in 0.000726s, 1377.5945 runs/s, 0.0000 assertions/s.
1 runs, 0 assertions, 0 failures, 0 errors, 0 skips
[Finished in 0.7s]