A Friendly Introduction to Software Testing by Bill Laboon

A Friendly Introduction to Software Testing by Bill Laboon

Author:Bill Laboon [Laboon, Bill]
Language: eng
Format: epub
Published: 2016-01-31T05:00:00+00:00


14.2 Stubs

If doubles are fake objects, stubs are fake methods. In the above examples, we didn’t care what calling .eat() on the DogFood object did; we just didn’t want it to call an actual DogFood object. In many cases, though, we expect a certain return value when a method is called. Let’s modify the .eat() method on DogFood so that it returns an integer indicating how tasty the dog food is:

public class Dog { public int eatDinner(DogFood df) { int tastiness = df.eatDinner(); return tastiness;

}

} If we were just using df as a normal test double, then there is no telling what df.eat() will return. Specifically, the answer varies by test framework—some will always return a default value, some will call out the real object, some will throw an exception. This should just be a piece of trivia, though—you shouldn’t call methods on a double object unless you have stubbed them. The whole reason for making a test double is so that you have an object that you have specified, instead of relying on external definitions. So let’s say that our doubled DogFood object has a (scientifically determined) tastiness level of 13. We can specify that whenever the .eat() method is called on our doubled object, then just return a value of 13. We have made a stub of the method:

public class DogTest {

@Test

public void testEatDinner() { Dog d = new Dog();

DogFood mockedDogFood = Mockito.mock(DogFood.class); when(mockedDogFood.eat()).thenReturn(13); int returnVal = d.eatDinner(mockedDogFood); assertEquals(13, returnVal);

}

} Now when the mockedDogFood object has its .eat() method called, it will return the value 13. Once again, we have quarantined the other methods by re-creating fakes of them that act as we think they should. In some languages, although not Java, we can even stub methods that don’t exist. This allows us to not only test classes that have errors, but even ones that don’t have all of their methods written yet.



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.