Search code examples
javaunit-testingenumsmockitofinal

Mocking an enum using Mockito?


I need to mock the following enum:

public enum PersonStatus
{
    WORKING,
    HOLIDAY,
    SICK      
}

This is because it is used in the following class that I am testing:

Class under test:

public interface PersonRepository extends CrudRepository<Person, Integer>
{
    List<Person> findByStatus(PersonStatus personStatus);
}

Here is my current test attempt:

Current test:

public class PersonRepositoryTest {

    private final Logger LOGGER = LoggerFactory.getLogger(PersonRepositoryTest.class);

    //Mock the PersonRepository class
    @Mock
    private PersonRepository PersonRepository;

    @Mock
    private PersonStatus personStatus;

    @Before
    public void setUp() throws Exception {

        MockitoAnnotations.initMocks(this);
        assertThat(PersonRepository, notNullValue());
        assertThat(PersonStatus, notNullValue());
    }

    @Test
    public void testFindByStatus() throws ParseException {

        List<Person> personlist = PersonRepository.findByStatus(personStatus);
        assertThat(personlist, notNullValue());
    }
}

Which Gives following error:

error:

org.mockito.exceptions.base.MockitoException: 
Cannot mock/spy class PersonStatus
Mockito cannot mock/spy following:
  - final classes
  - anonymous classes
  - primitive types

How can I solve this?


Solution

  • Your testFindByStatus is trying to assert that the findByStatus does not return null.

    If the method works the same way regardless of the value of the personStatus param, just pass one of them:

    @Test
    public void testFindByStatus() throws ParseException {
        List<Person> personlist = PersonRepository.findByStatus(WORKING);
        assertThat(personlist, notNullValue());
    }
    

    If the behaviour may be different for the other possible values, you can test each of them:

    @Test
    public void testFindByStatus() throws ParseException {
        for (PersonStatus status : PersonStatus.values()) {
            List<Person> personlist = PersonRepository.findByStatus(status);
            assertThat(personlist, notNullValue());
        }
    }