我需要模拟以下枚举:
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
我该如何解决这个问题?
最佳答案
只是为了完成图片:
最新版本的 Mockito 2 很好地支持模拟最终类。但是您必须首先明确启用这个新的实验性功能!
(请参阅 here 了解如何做到这一点 - 它归结为将文件 mockito-extensions/org.mockito.plugins.MockMaker
添加到您的类路径,其中包含值 mock -制造商内联
)
但是当然:只有在必要时才可以 mock 某些东西。您模拟 Enum 实例的愿望很可能是因为不理解这一点 - 或者因为您在这里创建了难以测试的代码。从这个意义上说,真正的答案是首先研究避免这种 mock 的方法。
关于java - 使用 Mockito 模拟枚举?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37049218/