I have written a simple unit test library for myself in Ruby over the past few days. It feels a little DSL.
It seems that there is no ruby format. Use Lua to make it together.
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