Java – use mockito to simulate enumeration?
•
Java
I need to simulate the following enumeration:
public enum PersonStatus { WORKING,HOLIDAY,SICK }
This is because it is used in the following classes I am testing:
Tested team:
public interface PersonRepository extends CrudRepository<Person,Integer> { List<Person> findByStatus(PersonStatus personStatus); }
This is my current test attempt:
Current tests:
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 the 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 problem?
Solution
Your testfindbystatus tried to assert that findbystatus does not return null
If the method works in the same way, regardless of the value of personstatus param, just pass one of them:
@Test public void testFindByStatus() throws ParseException { List<Person> personlist = PersonRepository.findByStatus(WORKING); assertThat(personlist,notNullValue()); }
If other possible values may behave differently, you can test each value:
@Test public void testFindByStatus() throws ParseException { for (PersonStatus status : PersonStatus.values()) { List<Person> personlist = PersonRepository.findByStatus(status); assertThat(personlist,notNullValue()); } }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码