2017-06-10 23 views
0

它要求實現類Tester,它接收一個類並運行所有以單詞test開頭的方法。如何製作Ruby測試器?

class AssertionFailed < Exception 
end 
class TestCase 
    def setUp 
    end 
    def tierDown 
    end 
    def assertTrue(expresion) 
    if not expresion then 
     raise AssertionFailed.new(expresion.to_s + " is not true") 
    end 
    end 
    def assertEquals(result, expected) 
    if result != expected 
     raise AssertionFailed.new(result.to_s + " is not equal to " + expected.to_s) 
    end 
    end 
end 
class IntegerTest < TestCase 
    def setUp 
    @number = 1 
    end 
    def testSum 
    assertTrue(1 + @number == 2) 
    @number += 1 
    end 
    def testSub 
    assertTrue(2 - @number == @number) 
    end 
    def testMulByZero 
    assertEquals(@number*0, 1) 
    end 
    def testAddByZero 
    assertEquals(@number + 0, @number + 1) 
    end 
end 

Tester.test(IntegerTest) 

實施例:

Tester.test(IntegerTest) 
[*] testMulByZero failed: 0 is not equals to 1 
[*] testAddByZero failed: 1 is not equals to 2 

幫助:了Iterable模塊的grep的方法接收正則表達式,並返回所有 匹配表達式的元素。對於練習,使用grep(\ test *) 獲取所需方法的方法集合。

+0

JFYI,像'testAddByZero'方法名稱不符合公認的命名約定。用名字命名的習慣用法是'test_add_by_zero'。一般來說,'camelCase'只是沒有用在紅寶石中。 –

回答

0

我終於通過這個source得到了一個答案,這個one 我所做的開始是給予測試,然後我問脫類testig與測試開始他instace創建一個數組,finaly它是一個迭代該陣列要求執行eachone的方法,如果他們失敗斷言然後告訴他們

class Tester 

def self.test(testing) 
    tested=testing.new 
    tested.setUp 
    method_arr=testing.instance_methods.grep(/test*/) 
    method_arr.each do |x| 
     begin 
     tested.send(:"#{x}") 
     rescue AssertionFailed =>assert_fail 
      puts "[*]" + "#{assert_fail}" 
     end 
    end 
end 

+0

只能使用'tested.send(x)' –