Writing Unit Tests : Unit Testing « Unit Test « Ruby






Writing Unit Tests


require 'test/unit'

class Person
  attr_accessor :first_name, :last_name, :age

  def initialize(first_name, last_name, age)
    raise ArgumentError, "Invalid age: #{age}" unless age > 0
    @first_name, @last_name, @age = first_name, last_name, age
  end

  def full_name
    first_name + ' ' + last_name
  end
end


class PersonTest < Test::Unit::TestCase
  def test_first_name
    person = Person.new('J', 'Y', 25)
    assert_equal 'J', person.first_name
  end

  def test_last_name
    person = Person.new('J', 'Y', 25)
    assert_equal 'Y', person.last_name
  end

  def test_full_name
    person = Person.new('J', 'Y', 25)
    assert_equal 'J Y', person.full_name
  end

  def test_age
    person = Person.new('J', 'Y', 25)
    assert_equal 25, person.age
    assert_raise(ArgumentError) { Person.new('J', 'Y', -4) }
    assert_raise(ArgumentError) { Person.new('J', 'Y', 'four') }
  end
end



# $ ruby test/person_test.rb

 








Related examples in the same category

1.The Philosophy of Test-Driven Development
2.Unit Testing: assert_equal
3.Test case setup
4.Unit Testing: hard code value
5.Test the values in an array
6.Assert exception raised
7.Structuring Tests
8.Varying the Algorithm with the Template Method
9.A test case for collection class