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
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)").
I'm new to Ruby. What am I missing here?
The problem is that
Test::Unit::TestCase
explicitly doesn't run tests defined in superclasses by default. In particular, note thatTestSuiteCreator
does not run tests unlessTest::Unit::TestCase#valid?
returns true (https://github.com/test-unit/test-unit/blob/2.5.5/lib/test/unit/testsuitecreator.rb#L40):And what determines if a test case is valid? A test case is valid by default if the this class explicitly defined that method, or if the method was defined in a
Module
(https://github.com/test-unit/test-unit/blob/2.5.5/lib/test/unit/testcase.rb#L405-L418):So basically, if you subclass another unit test class, and you want to run the superclass's unit tests, you can either:
valid?
method in your subclass to return true:def valid? return true end
The issue is that, as far as I can tell,
Test::Unit
keeps track of which classes inherit fromTest::Unit::TestCase
, and as a result, will only run tests from classes that directly inherit from it.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
.Output: