[Uw-ruby] mock unit testing...

Ryan Davis ryand-uwruby at zenspider.com
Wed Nov 7 15:31:36 PST 2007


On Nov 6, 2007, at 09:44 , Feng Tien wrote:

> The three programs I wrote for week5's homework all take user input  
> and I've tried writing tests but the unit test wouldn't let me put  
> in the inputs, it sets everything to 0.
>
> I was reading on the forum that you need to use mocks to get it to  
> work when the program is interactive, do you have any good examples  
> of this or can you talk about it in class tomorrow?
>
> BTW, can you tell me if I'm part of the mailing list, I haven't  
> received emails from the list, nor any emails from you about any  
> past homework.

This is a really good question so I thought I'd share.

1) It really depends on how you structure the design wrt user input.  
None of the classes you write like Account or Bank or whatever need to  
have any user input at all as they can simply take their input as  
arguments and return values as outputs.

   def deposit(amount)
     # ...
   end

but that really depends on your design...

2) If you do want to test user interaction, there are a couple ways to  
do it. Mocks are one. I prefer a simpler (some would say simplistic)  
approach:

503 % ruby -rstringio -e '$stdin = StringIO.new "hi\nexit\n"; p gets'
"hi\n"

But either way is fine.

BTW, this would be one of those places where teardown would be used.  
Putting things back in their place is a great example and I always  
forget it.



More information about the Uw-ruby mailing list