Created
January 30, 2020 10:36
-
-
Save muryoimpl/154cbc88796ddcc6e55b676e6110215e to your computer and use it in GitHub Desktop.
『テスト駆動開発』の第Ⅱ章の Ruby 版
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class TestCase | |
attr_reader :wasRun, :name, :wasSetUp | |
def initialize(name) | |
@wasRun = nil | |
@name = name | |
end | |
def setUp | |
true | |
end | |
def tearDown | |
true | |
end | |
def run(result) | |
result.testStarted | |
setUp | |
begin | |
method = @name | |
send(method) | |
rescue | |
result.testFailed | |
end | |
tearDown | |
end | |
def assert(condition) | |
raise unless condition | |
end | |
end | |
class TestSuite | |
attr_reader :tests | |
def initialize | |
@tests = [] | |
end | |
def add(test) | |
@tests << test | |
end | |
def run(result) | |
@tests.each do |test| | |
test.run(result) | |
end | |
end | |
end | |
class TestResult | |
attr_reader :runCount, :errorCount | |
def initialize | |
@runCount = 0 | |
@errorCount = 0 | |
end | |
def summary | |
'%d run, %d failed' % [@runCount, @errorCount] | |
end | |
def testStarted | |
@runCount += 1 | |
end | |
def testFailed | |
@errorCount += 1 | |
end | |
end | |
class WasRun < TestCase | |
attr_reader :log | |
def setUp | |
@log = "setUp " | |
end | |
def testMethod | |
@log += "testMethod " | |
end | |
def tearDown | |
@log += 'tearDown ' | |
end | |
def testBrokenMethod | |
raise | |
end | |
end | |
class TestCaseTest < TestCase | |
attr_reader :result | |
def setUp | |
@result = TestResult.new | |
end | |
def testTemplateMethod | |
test = WasRun.new('testMethod') | |
test.run(result) | |
assert('setUp testMethod tearDown ' == test.log) | |
end | |
def testResult | |
test = WasRun.new('testMethod') | |
test.run(result) | |
assert('1 run, 0 failed' == result.summary) | |
end | |
def testFailedResult | |
test = WasRun.new('testBrokenMethod') | |
test.run(result) | |
assert('1 run, 1 failed' == result.summary) | |
end | |
def testFailedResultFormatting | |
result.testStarted | |
result.testFailed | |
assert('1 run, 1 failed' == result.summary) | |
end | |
def testSuite | |
suite = TestSuite.new | |
suite.add(WasRun.new('testMethod')) | |
suite.add(WasRun.new('testBrokenMethod')) | |
suite.run(result) | |
assert('2 run, 1 failed' == result.summary) | |
end | |
def result | |
@result | |
end | |
end | |
suite = TestSuite.new | |
suite.add(TestCaseTest.new('testTemplateMethod')) | |
suite.add(TestCaseTest.new('testResult')) | |
suite.add(TestCaseTest.new('testFailedResult')) | |
suite.add(TestCaseTest.new('testFailedResultFormatting')) | |
suite.add(TestCaseTest.new('testSuite')) | |
result = TestResult.new | |
suite.run(result) | |
puts result.summary |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment