Test Doubles
Intro
Imagine we're making a checking application. We don't want to check real transactions in order to test our app. Hence we use doubles
Double=fake data
Types
stub
fake
spy
mock
Dummy
Double as in stunt double. Replaces the star actor when the actor isn't available to perform
click to edit
dummy
Uses
Avoid NullPointerException
Allows us to create a fake instance of a class
Advanced Mockito
General
When it comes to testing we care about the logic
Let's say we want to test how our app displays the latest stock information. As a programmer we don't care about the stock information. We care how the app displays it.
Then why spend extra time creating a connection to stock information and increasing test time?
Limitations
Can't mock:
enums
tatic methods, private methods
final classes, final methods
hashCode(), equals() methods
anonymous classes
primative types
Solution is mocking those external dependencies
Stock example
Let's say we had an app for stocks. If we had a method that requires a Portfolio (we'd need a database to retreive stored information) and StockRetreiver (We'd need the Internet to connect to)
This greatly increases our test type needlessly
Mock objects allow us to imitate these Classes without doing all the hardcore work required
Remember key point is to test logic
Syntax
The annotation allows us to mock an object
Mock
Portfolio portfolio;
This creates a mock object of Portfolio
This requires us to initialize annotations or done if we RunWith Mockito
MockitoAnnotations.initMocks(this)
Usually done in Before
Definies the behavior of mock methods
What should be returned or what exceptions should be thrown
Stubbing
Mockito offers when and thenReturn to allow us to return a given value when a specific method is called
when(marketWatcher.getQuote(anyString())).thenReturn(uvsityCorp);
This says whenever the get quote function is called with any string as the parameter, return uvsityCorp
So if later on we call getQuote method it'll return what we specified