我需要模拟以下枚举:
public enum PersonStatus
{
WORKING,
HOLIDAY,
SICK
}
这是因为它在我正在测试的以下类中使用:
被测班:
public interface PersonRepository extends CrudRepository<Person, Integer>
{
List<Person> findByStatus(PersonStatus personStatus);
}
这是我目前的测试尝试:
目前的测试:
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());
}
}
哪个给出以下错误:
错误:
org.mockito.exceptions.base.MockitoException:
Cannot mock/spy class PersonStatus
Mockito cannot mock/spy following:
- final classes
- anonymous classes
- primitive types
我怎么解决这个问题?
你的testFindByStatus
试图断言findByStatus
不会返回null。
如果该方法以相同的方式工作,无论personStatus
参数的值如何,只需传递其中一个:
@Test
public void testFindByStatus() throws ParseException {
List<Person> personlist = PersonRepository.findByStatus(WORKING);
assertThat(personlist, notNullValue());
}
如果其他可能值的行为可能不同,您可以测试每个值:
@Test
public void testFindByStatus() throws ParseException {
for (PersonStatus status : PersonStatus.values()) {
List<Person> personlist = PersonRepository.findByStatus(status);
assertThat(personlist, notNullValue());
}
}
只是为了完成图片:
最新版本的Mockito 2非常支持模拟最终课程。但是你必须首先明确启用这个新的实验功能!
(请参阅here关于如何做到这一点 - 归结为将mockito-extensions/org.mockito.plugins.MockMaker
文件添加到类路径中,包含值mock-maker-inline
)
但当然:如果必须,你只会嘲笑某事。你想要模拟Enum实例的愿望很可能是由于不了解 - 或者因为你在这里创建了难以测试的代码。从这个意义上说,真正的答案是首先考虑避免这种嘲弄的方法。