0

So im trying to test my service layer and i have mocked my repository, what i want to do is

@ExtendWith(MockitoExtension.class)
public class TicketServiceTest {

    @Mock
    private TicketRepository ticketRepository;

    @InjectMocks
    private TicketService ticketService;

    @Test
    public void test_buy_ticket_successfully() {
        Ticket ticket = new Ticket(1, false, false, "");
        List<Ticket> availableTickets = Arrays.asList(ticket);

        Mockito.when(ticketRepository.findAllUnboughtAndUnpickedTickets()).thenReturn(availableTickets);
        Mockito.when(ticketRepo.findById(any(Integer.class)).thenReturn(Optional.of(any(Ticket.class));

        Ticket boughtTicket = ticketService.buyTicket("123");

        assertNotNull(boughtTicket);
        assertEquals(1, boughtTicket.getId());

        Mockito.verify(ticketRepository).findAllUnboughtAndUnpickedTickets();

    }

Error i get is :

Type mismatch: cannot convert from Matcher<Integer> to Integer

All i want to do is use any matchers in the input and output, but this does not work as my repoistory is as follows:

public interface TickRep extends JpaRepository<Ticket, Integer>

Im using spring boot, junit 5.

Any ideas?

user1555190
  • 2,803
  • 8
  • 47
  • 80

1 Answers1

1

There is a problem with the line setting expectations:

thenReturn(Optional.of(any(Ticket.class));

The error you get

Type mismatch: cannot convert from Matcher<Integer> to Integer

suggests that you are using Hamcrest matchers, not Mockito matchers.

See Mockito's Matcher vs Hamcrest Matcher?

  • Mockito any() returns T,
  • Hamcrest any() returns Matcher<T>

Second problem: even Mockito matchers cannot be used in context of a return value.

See: How do Mockito matchers work?

Matcher methods can't be used as return values; there is no way to phrase thenReturn(anyInt()) or thenReturn(any(Foo.class)) in Mockito, for instance. Mockito needs to know exactly which instance to return in stubbing calls, and will not choose an arbitrary return value for you.

Lesiak
  • 22,088
  • 2
  • 41
  • 65