如何在Ruby中继承抽象单元测试

如何在Ruby中继承抽象单元测试

本文介绍了如何在Ruby中继承抽象单元测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个单元测试,应该使用略有不同的设置方法共享许多常见测试。如果我写的东西像

I have two unit tests that should share a lot of common tests with slightly different setup methods. If I write something like

class Abstract < Test::Unit::TestCase
  def setup
    @field = create
  end

  def test_1
    ...
  end
end

class Concrete1 < Abstract
  def create
    SomeClass1.new
  end
end

class Concrete2 < Abstract
  def create
    SomeClass2.new
  end
end

然后Concrete1似乎没有从Abstract继承测试。或者至少我不能让它们在日食中运行。如果我为包含Concrete1的文件选择Run all TestCases,那么即使我不想要它也会运行Abstract。如果我指定Concrete1那么它根本不运行任何测试!如果我在Concrete1中指定test_1,那么它会抱怨它无法找到它(uncaught throw:invalid_test(ArgumentError))。

then Concrete1 does not seem to inherit the tests from Abstract. Or at least I cannot get them to run in eclipse. If I choose "Run all TestCases" for the file that contains Concrete1 then Abstract is run even though I do not want it to be. If I specify Concrete1 then it does not run any tests at all! If I specify test_1 in Concrete1 then it complains it cannot find it ("uncaught throw :invalid_test (ArgumentError)").

我是Ruby的新手。我在这里缺少什么?

I'm new to Ruby. What am I missing here?

推荐答案

问题在于,据我所知,测试:: Unit 跟踪哪些类继承自 Test :: Unit :: TestCase ,因此只会 直接继承的类中运行测试。

The issue is that, as far as I can tell, Test::Unit keeps track of which classes inherit from Test::Unit::TestCase, and as a result, will only run tests from classes that directly inherit from it.

解决此问题的方法是创建一个包含所需测试的模块,然后包含 Test :: Unit :: TestCase 派生的类中的模块。

The way to work around this is to create a module with the tests you want, and then include that module in the classes that derive from Test::Unit::TestCase.

require 'test/unit'

module TestsToInclude
  def test_name
    assert(self.class.name.start_with?("Concrete"))
  end
end

class Concrete1 < Test::Unit::TestCase
  include TestsToInclude

  def test_something_bad
    assert(false)
  end
end

class Concrete2 < Test::Unit::TestCase
  include TestsToInclude

  def test_something_good
    assert(true)
  end
end

输出:


Loaded suite a
Started
.F..
Finished in 0.027873 seconds.

  1) Failure:
test_something_bad(Concrete1) [a.rb:13]:
<false> is not true.

4 tests, 4 assertions, 1 failures, 0 errors

shell returned 1

这篇关于如何在Ruby中继承抽象单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 07:25