From: Ryan Leavengood Date: 2005-05-11T08:17:12+09:00 Subject: Re: Testing a user application Vincent Foley wrote: > > Ryan Levengood suggested in another thread that I use mock objects for > my testing purposes, but I don't understand clearly how they work. I'm back with your example. To use this, change the initialize for LiveJournalClient to this: def initialize(username, hpassword, &block) @username, @password = username, hpassword if block @server = block.call else @server = XMLRPC::Client.new("www.livejournal.com", "/interface/xmlrpc", 80) end end Here is the new test_ljclient.rb: require "lib/ljclient" require "test/unit" require "digest/md5" class MockServer attr_reader :method, :hash def initialize @exception = nil end def call(method, hash={}) @method = method @hash = hash if @exception raise @exception.new('test', 'test') end end def do_raise(exception) @exception = exception end end class TestLiveJournalClient < Test::Unit::TestCase def initialize(name) super(name) @username = "test" @password = Digest::MD5.hexdigest("test") @client = create_client(@username, @password) end def create_client(username, password) LiveJournalClient.new(username, password) do @server = MockServer.new end end def test_login assert_nothing_raised(Exception) { @client.login } assert_equal('LJ.XMLRPC.login', @server.method) assert_equal(@username, @server.hash[:username]) assert_equal(@password, @server.hash[:hpassword]) bad_login = create_client("aosidoasndoiashd908h12", "") @server.do_raise(XMLRPC::FaultException) # Really this XMLRPC exception should be mapped to another # exception, like RJournal::InvalidLoginException assert_raise(XMLRPC::FaultException) { bad_login.login } bad_password = create_client(@username, "") @server.do_raise(XMLRPC::FaultException) # Same here, except it should be RJournal::InvalidPasswordException assert_raise(XMLRPC::FaultException) { bad_password.login } end def test_post subject = 'This is a subject' event = 'This is an event' assert_nothing_raised { @client.post(subject, event) } assert_equal('LJ.XMLRPC.postevent', @server.method) assert_equal(@username, @server.hash[:username]) assert_equal(@password, @server.hash[:hpassword]) assert_equal(subject, @server.hash[:subject]) assert_equal(event, @server.hash[:event]) # The other parts of the hash should also be tested end end