gpt4 book ai didi

ruby 迷你测试 : Suite- or Class- level setup?

转载 作者:数据小太阳 更新时间:2023-10-29 06:43:45 25 4
gpt4 key购买 nike

使用内置的 Ruby Minitest 框架,有没有办法在整个套件运行之前运行一些代码,甚至在整个 TestClass 运行之前运行一次?我在 this question 的答案中看到Test::Unit::after_tests 可用于在运行所有测试后运行代码;是否有类似的方法在所有测试运行之前运行代码?

我想使用此功能在测试运行前初始化测试数据库,并在测试全部运行后将其拆除。

谢谢!

最佳答案

这是从 MiniTest 修改而来的 docs (在可自定义的测试运行器类型下)。

class Burger
def initialize
puts "YOU CREATED A BURGER"
end

def has_cheese?
true
end

def has_pickle?
false
end
end

gem 'minitest'

require 'minitest/unit'
MiniTest::Unit.autorun

class MyMiniTest
class Unit < MiniTest::Unit

def before_suites
# code to run before the first test
p "Before everything"
end

def after_suites
# code to run after the last test
p "After everything"
end

def _run_suites(suites, type)
begin
before_suites
super(suites, type)
ensure
after_suites
end
end

def _run_suite(suite, type)
begin
suite.before_suite if suite.respond_to?(:before_suite)
super(suite, type)
ensure
suite.after_suite if suite.respond_to?(:after_suite)
end
end

end
end

MiniTest::Unit.runner = MyMiniTest::Unit.new

class BurgerTest < MiniTest::Unit::TestCase

def self.before_suite
p "hi"
end

def self.after_suite
p "bye"
end

def setup
@burger = Burger.new
end

def test_has_cheese
assert_equal true, @burger.has_cheese?
end

def test_has_pickle
assert_equal false, @burger.has_pickle?
end

end

请注意,我包含了 gem 'minitest' 以使用 gem 而不是没有 MiniTest::Unit.runner 方法的捆绑版本。这是输出。

Run options: --seed 49053

# Running tests:

"Before everything"
"hi"
YOU CREATED A BURGER
.YOU CREATED A BURGER
."bye"
"After everything"


Finished tests in 0.000662s, 3021.1480 tests/s, 3021.1480 assertions/s.

2 tests, 2 assertions, 0 failures, 0 errors, 0 skips

所以它调用 #setup 两次,但是 .before_suite.after_suite 只调用一次,我想这就是你要找的。

关于 ruby 迷你测试 : Suite- or Class- level setup?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6756488/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com