もっと、みやびちゃんぷりちー!

みやびちゃんぷりちー!

RubyでUnit Test

Rubyの書き方とテスト駆動開発を進めるために調査と実践

Ruby入門とコンストラクタの注意事項
Ruby “ü–å
アクセスメソッド - クラスの概念 - Ruby入門
【Ruby】 複数のinitializeは定義できない? - ぽっくるのITざっき

テストコードの書き方
Ruby Reference Manual
mock の使いどころが少しわかってきた - 刺身☆ブーメランのはてなダイアリー

で不細工な内容ですが、簡単に書いてみました。

#
# テスト対象クラス
#
class MyModel
  attr_accessor:name
  attr_accessor:times

  def initialize(name=nil, times=nil)
    @name = "初期化だけ"
    @times = 0
    unless name.nil?
      @name = name 
    end
    unless times.nil?
      @times = times
    end
  end

  def printTitle
    title = (name * times)
    puts(title)
    return title
  end
end

#
# テストコード
#
require 'test/unit'
require 'mocha'
require 'src/model/MyModel'

class MyModelTest < Test::Unit::TestCase
  def testGetName
    model = MyModel.new()
    assert_not_nil(model.name, "Not Nil")
  end

  def testGetTimes
    model = MyModel.new()
    assert_equal(0, model.times, "Is zero")
  end

  def testPrintTitle
    model = MyModel.new("おはよう ", 5)
    assert_match("おはよう おはよう おはよう おはよう おはよう ", model.printTitle(), "If not match, so ....")
  end
end

実行結果は以下になりました