Mocking In Many Languages

Let's pretend that you have a legacy report function, called "run_report()" (every company has one of those, don't they?). Your customer wants it to send the report by email after it's done.

Surely you don't want to actually send a mail every time you run your tests, so you mock.

Presume you have a working "Email" class. It has a "send_it" method that you need to mock. Here's how you do it in various languages:

PerlLanguage (Using typeglobs, anonymous subs and Test::More)

 {
  my @args;
  local *Email::send_it = sub { @args = @_ };
  my $email = Email->new();
  run_report($email);
  is_deeply(\@args, [ $email, 'The report went like so...' ]);
 }

RubyLanguage (using RubyMock and RubyTestUnit)
 email = Mock.new()
 email.__next(:send_it) do |message|
  assert_equal('The report went like so...', message)
 end
 run_report(email)
 email.__verify

PythonLanguage (using PythonUnit)
 class MockEmail(TestCase): # inherits from TestCase because assertions are not their own class
   def send_it(self, message):
     self.assertEqual(message, 'The report went like so...')
 email = MockEmail()
 run_report(email)

PhpLanguage (using SimpleTest)
 Mock::generate("Email");    // Usually at top of test file
 $email = &new MockEmail($this);
 $email->expectOnce("send_it", array('The report went like so...'));
 run_report($email);
 $email->tally();


These tests are doing different things: some fail as soon as an invalid message is sent (as MockObjects should) while others store the message and test its validity after the fact.


I would really like to see the same thing in FORTRAN for my department, but their FortranCompiler? has no interface at all to the EmailSystem. It's so sad... --ChrisGarrod


CategoryInManyProgrammingLanguages


EditText of this page (last edited June 8, 2008) or FindPage with title or text search