Skip to content

Instantly share code, notes, and snippets.

@ChristinGorman
Created October 24, 2015 11:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ChristinGorman/4bf388b7184002a07931 to your computer and use it in GitHub Desktop.
Save ChristinGorman/4bf388b7184002a07931 to your computer and use it in GitHub Desktop.
/*Example of how you can rewrite your code to avoid the need for mocks in your tests */
/*-----------------------------------------------
Implementation where you need mocks for testing
-------------------------------------------------*/
public class MyClassThatNeedsTesting {
private BusinessLogicClass blc;
public int estimatedTotalCost(SomeDataStructure input) {
int size = input.something.size();
int factor = size > 3 ? 1 : 1.5;
return size * a – b / blc.foo() + factor;
/* whatever – just some calculation worthy of testing that uses input from the business logic class */
}
}
/*To test this you need to mock the BusinessLogicClass and specify what to return in the foo() method. */
public class MyClassThatNeedsTestingTest {
public void should_do_the_right_thing() {
MyClassThatNeedsTesting myTestObject = new MyClassThatNeedsTesting();
BusinessLogicClass mock = mock(BusinessLogicClass.class);
when(mock.foo()).thenReturn(5);
assertEquals(10, myTestObject.estimatedTotalCost(formData);
}
}
/*-----------------------------------------------
Implementation without need for mocks in testing
-------------------------------------------------*/
public class MyClassThatNeedsTesting {
private BusinessLogicClass blc;
public int estimatedTotalCost(MyFormData input) {
return estimatdTotalCost(input.something.size(), blc.foo());
}
/* extracted the test-worthy stuff into a separate function that just takes the necessary parameters as input */
int estimatedTotalCost(int size, int foo) {
int factor = size > 3 ? 1 : 1.5;
return size * a – b / foo + factor;
}
}
/*Now you can test the implementation without mocking, just by sending whatever values for foo into the calculation function. */
public class MyClassThatNeedsTestingTest {
public void should_still_do_the_right_thing() {
assertEquals(10, new MyClassThatNeedsTesting().estmatedTotalCost(3, 5);
}
}
/* Much easier to test. No mocks required */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment