1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
|
package com.apside.prono.test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.when;
import java.util.Optional;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import com.apside.prono.model.Player;
import com.apside.prono.repository.PlayerRepository;
import com.apside.prono.repository.PlayerRepositoryImpl;
import com.apside.prono.service.PlayerServiceImpl;
/**
*
* https://static.javadoc.io/org.mockito/mockito-core/2.23.0/org/mockito/Mockito.html
*
*/
@RunWith(MockitoJUnitRunner.class)
@ContextConfiguration(classes = { PlayerServiceImpl.class , PlayerRepositoryImpl.class })
public class PlayerPronoTest {
@Mock
private PlayerRepository<Player, Long> playerRepository;//= mock(PlayerRepository.class);
@Autowired
@InjectMocks
private PlayerServiceImpl playerService;
@Test
public void canGetPlayerById() {
System.out.println("playerRepository = " + playerRepository.getClass());
System.out.println("playerService = " + playerService.getClass());
//configure playerRepository's mock (to avoid DB access when calling the service)
final Player player = new Player();
player.setId(2L);
player.setName("secondPlayer");
when(playerRepository.findById(2L)).thenReturn(Optional.of(player));
//now use the mock : call the playerService that relies on playerRepository's mock
final Optional<Player> actual = playerService.getPlayerById(2L);
System.out.println("actual=" + actual);
assertNotNull(actual);
assertTrue(actual.isPresent());
assertEquals(2L, actual.get().getId());
}
} |
Partager