-
-
Save tamboer/c4188495b7da70dcf1a770055d33a6b7 to your computer and use it in GitHub Desktop.
Mockito Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example.tdd; | |
import java.math.BigDecimal; | |
public class UtilizationController { | |
private CalculatesAverage calculatesAverage; | |
private CountsHoursInMonth countsHoursInMonth; | |
private AccumulatesActualsInMonth accumulatesActualsInMonth; | |
public BigDecimal calculate(Integer month, Integer year) { | |
return calculatesAverage.calculate( | |
countsHoursInMonth.count(month, year), | |
accumulatesActualsInMonth.accumulate(month, year)); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example.tdd; | |
import static org.junit.Assert.*; | |
import java.math.BigDecimal; | |
import static org.mockito.Mockito.*; | |
import org.junit.Test; | |
import org.junit.runner.RunWith; | |
import org.mockito.InjectMocks; | |
import org.mockito.Mock; | |
import org.mockito.runners.MockitoJUnitRunner; | |
@RunWith(MockitoJUnitRunner.class) | |
public class UtilizationControllerTest { | |
@InjectMocks private UtilizationController subject; | |
@Mock private CalculatesAverage calculatesAverage; | |
@Mock private CountsHoursInMonth countsHoursInMonth; | |
@Mock private AccumulatesActualsInMonth accumulatesActualsInMonth; | |
@Mock private DogRepository dogRepository; | |
@Test | |
public void calculatesAverageBasedOnActualsAndAvailable() { | |
Integer month = 2; | |
Integer year = 1999; | |
Integer totalAvailableHours = 98765; | |
Integer totalActualHours = 12345; | |
when(countsHoursInMonth.count(month, year)).thenReturn(totalAvailableHours); | |
when(accumulatesActualsInMonth.accumulate(month, year)).thenReturn(totalActualHours); | |
when(calculatesAverage.calculate(totalAvailableHours, totalActualHours)).thenReturn(new BigDecimal("12.34")); | |
BigDecimal result = subject.calculate(month , year); | |
assertEquals(new BigDecimal("12.34"), result); | |
} | |
@Test | |
public void savesDog() { | |
Object dog = new Object(); | |
dogRepository.save(dog); | |
verify(dogRepository).save(dog); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment