rasilvap
rasilvap

Reputation: 2179

Mocked response is not working and the real method is invoked

I am working with mockito and I am trying to test a get method from my service, The problem is that the test is invoking the real method and for that reason it is not working at all. The next is the method that I would like to test:

     public Hours getHours(String id) throws IllegalArgumentException {
        logger.debug("getting id {}", id);
        try {
          return repository.get(validateUuid(id).toString());
        } catch (Exception e) {
          logger.error("there was an issue querying with id {}", id, e);
          publishError("get", e);
          throw new IllegalArgumentException(
              String.format("there was an issue querying with id {%s}", id));
        }
    }

    private UUID validateUuid(String id) {
        try {
          return UUID.fromString(id);
        } catch (Exception e) {
          throw new IllegalArgumentException("the id given was was invalid", e);
        }
    }

This is the code of my test:

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.BDDMockito.given;
import static org.mockito.Matchers.*;
import static org.mockito.Mockito.when;

class serviceTest {

    @Mock
    private Repository<Hours> repository;
    private Service service;

    @BeforeEach
    public void init() {
        MockitoAnnotations.initMocks(this);
        service = new service();
    }

    @Test
    void addHours() {
        Hours hours = new Hours();
        hours.setCorrelationId("a-988787888b712ijj-0997878");
        hours.setPerner("720022");

        given(repository.post(any(Hours.class), anyBoolean())).willReturn(hours);

        Hours persistedHours = service.addHours(hours);

        assertEquals(persistedHours, hours);
    }

    @Test
    void getHours() {
        String mockedUUID = UUID.randomUUID().toString();
        Hours hours = new Hours();
        Hours.setCorrelationId("a-988787888b712ijj-0997878");

        when(repository.get(mockedUUID)).thenReturn(hours);

        Hours persistedHours = service.getHours(mockedUUID);

        assertEquals(persistedHours.getCorrelationId(), hours.getCorrelationId());
    }

    @Test
    void getHousrAll() {
        List<Hours> hoursList  = new ArrayList<>();
        PaginatedResult<Hours> result = new PaginatedResult<>();
        result.setResult(hoursList);

        given(repository.get(any(Query.class))).willReturn(result);

        PaginatedResult<Hours> result2 = service.getHousrAll(new Query());

        assertEquals(result , result2);
    }
}

I've also used:

given(banquetLaborHoursRepository.get(anyString())).willReturn(banquetLabourHours);

But the result was the same. Any ideas?

Upvotes: 0

Views: 1013

Answers (2)

Umar Tahir
Umar Tahir

Reputation: 625

This can help you. Normally when you do testing you set dependency into mocked object. Here Repository being dependency for YourService. @InjectsMock is basically setting repository mock object into your service.

But If you dont want to use annotations you need to create a mock object of service and a mock object of repository and set that into service mock object. That will work too but annotations like InjectsMock reduce code for us.

 @RunWith(MockitoJUnitRunner.class)
    class GameTester {

    @InjectMocks
    YourService service;
    @Mock
    Repository repository;

    @Test
        void getHours() {
            Hours hours = new Hours();
            hours.setCorrelationId("a-988787888b712ijj-0997878");
            when(repository.get(mockedUUID)).thenReturn(hours);

            Hours persistedBanquet = service.getHours("a-988787888b712ijj-0997878");
            assertEquals(persistedBanquet.getCorrelationId(), hours.getCorrelationId());
        }
}

Upvotes: 1

Rahul Vedpathak
Rahul Vedpathak

Reputation: 1436

@Test
void getHours() {
    // This generates a different uuid everytime
    String mockedUUID = UUID.randomUUID().toString();
    Hours hours = new Hours();
    hours.setCorrelationId("a-988787888b712ijj-0997878");

    // Use mockito.anyString() instead of passing this uuid
    given(repository.get(mockedUUID)).willReturn(hours);

    Hours persistedBanquet = 
     service.getHours(mockedUUID);

    assertEquals(persistedBanquet.getCorrelationId(), 
     hours.getCorrelationId());
}

Instead of mocking on single string entity i.e. uuid value, pass Mockito.anyString(). So the method will be mocked for any string as argument to repository.

Else instead of generating uuid everytime, use a same uuid value like a static variable and mock on it using mockito.eq(static_uuid) method.

Upvotes: 0

Related Questions