这几天在学ruby, 自己写了一个简单的单元测试库, 有点DSL的感觉。
似乎没有ruby的格式化, 用Lua凑合一下吧。
sample code:
require 'rUnit'
include RUnit
testSuite :SampleTestSuite do
setup do
end
tearDown do
end
testCase :TestEqualPass do
assertEqual 1.0, 4.0-3.0
end
testCase :TestEqualFail do
assertEqual 1, 2
end
testCase :TestFail do
assert 1>3
end
testCase :TestException do
raise 'Exception raised'
end
end
Output:
SampleTestSuite
Passed:TestEqualPass
Failed:TestEqualFail (Expected <1> but <2>.)
Failed:TestFail (Expected <true> but <false>)
Failed:TestException (Exception raised)
Lib Source:
rUnit
module RUnit
class TestSuite
attr_reader :name
attr_accessor :setup, :teardown
def initialize(name)
@name = name
@testCases = []
end
def addTestCase(testCase)
@testCases << testCase
self
end
def run()
@testCases.collect do |tc|
begin
@setup.run if @setup
tc.run
ensure
@teardown.run if @teardown
end
end
end
end
class SetUp
def initialize(block)
@block = block
end
def run
@block.call
end
end
class TearDown < SetUp
end
class TestCase
attr_reader :name
def initialize(name, block)
@name = name
@block = block
end
def run()
@block.call()
TestResult.new(@name, true)
rescue =>ex
TestResult.new(@name,false,ex)
end
end
class TestResult
attr_reader :message,:status,:testCaseName
def initialize(testCaseName, status, message=nil)
@testCaseName = testCaseName
@status = status
@message = message
end
end
def printResult(name,results)
puts name
results.each do |r|
status = :Failed
status = :Passed if r.status
message = "\t#{status}:#{r.testCaseName}"
message += " (#{r.message})" if r.message
puts message
end
end
module_function
def testSuite(name, &block)
@testSuite = TestSuite.new(name)
block.call
results = @testSuite.run
printResult(name, results)
end
def testCase(name, &block)
@testSuite.addTestCase TestCase.new(name, block)
end
def setup(&block)
raise 'Test suite can have only one setup method' if @testSuite.setup
@testSuite.setup = SetUp.new(block)
end
def tearDown(&block)
raise 'Test suite can have only one teardown method' if @testSuite.teardown
@testSuite.teardown = TearDown.new(block)
end
def assert(expression)
assertFail 'Expected <true> but <false>' unless expression
end
def assertEqual(expected, actual)
assertFail "Expected <#{expected}> but <#{actual}>." unless expected == actual
end
def assertFail(message)
raise message
end
end