Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any way to verify that mocks or stubs are valid?

Say I have a class and method defined with the following pseudo code

class Book
  def quick_info
    return title + " " + author
  end
end

If I'm writing a unit test on some other class that uses this Book class I'd create a stub for the method call to Book.quick_info.

Now I figure a problem would arise if my Book class were to change, for example if the quick_info method was renamed to short_description. My unit test would still be using quick_info and it would look like my tests are passing just fine when in fact it should be failing.

I was wondering if there's something that could be run to verify that the stubs/mocks in my test were actually made up of the correct classes and methods. Maybe something like this could be run on a continuous integration server just to verify that things match up?

Hrmm....and now a thought just occurred to me. Is it even possible to create a mock/stubbed method that doesn't exist? If not, then this whole question is moot.

EDIT:

I just tried this out using rspec 2 and I know I can create a Book instance and create a method named i_dont_exist and I can call it just fine. So my question still stands. Is there a way to verify my mocks/stubs match up to the classes/objects that are really there?

like image 235
Fendo Avatar asked Oct 12 '22 13:10

Fendo


1 Answers

Mocha has an option for this:

Mocha::Configuration.prevent(:stubbing_non_existent_method)

Though it requires you to mock an existing object. If you are creating a mock from 'scratch' it won't work (since it has no idea what methods should be there).

In terms of best practices, IMHO you are looking at it from wrong direction. You should have unit test on Book class as well, so you will get test failures when you rename the method. That should be strong enough signal to 'grep' the code to see if there are more calls to this method.

Also (unless this is just an example) why would you want to mock Book anyway? It's just a data - you usually want to mock external services and such and work with real data objects in your tests.

like image 66
Gregory Mostizky Avatar answered Oct 15 '22 11:10

Gregory Mostizky