Skip to content

Instantly share code, notes, and snippets.

@ram0973
Last active March 14, 2021 09:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ram0973/9c1b9e216c33e6942f69b2797d642d6b to your computer and use it in GitHub Desktop.
Save ram0973/9c1b9e216c33e6942f69b2797d642d6b to your computer and use it in GitHub Desktop.
Java Mockito example
// Let's consider an example. UsdConverter class is responsible for converting local currency to USD (United States dollar).
// The test should check the behavior of the tested unit in isolation from its dependencies.
// As the exchange rate varies with time, UsdConverter uses ExchangeRateService to get the latest updates.
// Moreover, getUsd method of a live ExchangeRateService can send a request over HTTP to get the actual exchange rate,
// which is difficult to reproduce in the test environment.
// Mockito allows us to avoid those difficulties and provides an API for creating empty objects and managing behavior.
// Note: here we use BigDecimal since financial transactions need high accuracy:
public class UsdConverter {
private ExchangeRateService service;
public UsdConverter(ExchangeRateService service) {
this.service = service;
}
public BigDecimal convertToUsd(BigDecimal converted) {
return converted.multiply(service.getUsd());
}
}
// Using mockito, we create a mock of ExchangeRateService object and define its behavior in case of getUsd method invocation:
import org.junit.Assert;
import org.mockito.Mock;
public class UsdConverterTest {
@Mock
private ExchangeRateService service = Mockito.mock(ExchangeRateService.class);
private UsdConverter converter = new UsdConverter(service);
@Test
public void testConvertToUsd() {
Mockito.when(service.getUsd()).thenReturn(BigDecimal.valueOf(5));
BigDecimal result = converter.convertToUsd(BigDecimal.valueOf(2));
BigDecimal expected = BigDecimal.valueOf(10);
Assert.assertEquals(expected, result);
}
}
// You can also throw an exception on a method call to test error handling.
// Another useful feature is checking that method was invoked inside the tested method.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment