Replacing Troublesome Behavior with Stubs

Let’s focus first on verifying how we populate an Address using the JSON response from the HTTP call. To do that, we’d like to change the behavior of HttpImpl’s get() method—just for purposes of the test we want to write—so that it returns a hardcoded JSON string. An implementation that returns a hardcoded value for purposes of testing is known as a stub.

HttpImpl implements the functional Http interface. Create a stub implementation dynamically using lambdas:

Http http = (​String​ url) ->
+ ​"\"house_number\":\"324\","
+ ​"\"road\":\"North Tejon Street\","
+ ​"\"city\":\"Colorado Springs\","
+ ​"\"state\":\"Colorado\"," ...

Get Pragmatic Unit Testing in Java 8 with JUnit now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.