我在我的项目中使用 Mockito 和 Spring Framework。
我有一个这样的测试用例:
class SomeTest {
@Mock
SomeDao dao;
@InjectMock
TestTarget target;
class MyAnswer implements Answer {
//some method here
}
}
我想为 dao
定义一个自定义 Answer 类 MyAnswer
。
如果没有注释,我可以使用 Mockito.mock(Dao.class, new MyAnswer())
强制我的模拟对象使用 MyAnswer。但我发现使用 @Mock
注释,它们只接受 enum Answers
内部的参数,例如 Answers.RETURNS_DEFAULT
或 Answers.RETURNS_MOCKS
.
我可以强制 dao
使用带有 @Mock
注释的 MyAnswer
吗?
最佳答案
很遗憾,您必须为此使用 Mockito.mock
。目前无法指定您通过@Mock 编写的答案。
原因与 Mockito 无关,而与 Java 的注释规范有关:
Parameters may only be typed as a primitive, String, Class, enum, annotation, or an array of any of these. (Jason Hunter, "Making the Most of Java's Metadata, Part 2: Custom Annotations")
并且在 Java Language Specification §9.6.1 :
The return type of a method declared in an annotation type must be one of the following, or a compile-time error occurs:
- A primitive type
- String
- Class or an invocation of Class (§4.5)
- An enum type
- An annotation type
- An array type whose component type is one of the preceding types (§10.1).
因为注释类型元素必须是有效的 VM 范围常量(包括枚举值但不包括任意实例),所以无法放置您创建的答案实例。理论上,Mockito 可以让您指定一个命名的 Answer 子类,但是 Mockito 也将负责实例化它,这并不总是可能的,并且会导致运行时失败。如果该功能对您很重要,您可以考虑制作 feature request .
关于java - 在 Mockito 中使用自定义 Answer 类的 @mock 注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42423512/