我想使用 Mockito 对 toEntity 函数执行 junit 测试。
@Component
public class MyEntityTransform {
public Function<MyDTO , MyEntity> toEntity = new Function<MyDTO , MyEntity >() {
@Override
public MyEntity apply(MyDTO record) {
return new MyEntity();
}
};
}
不幸的是,当我模拟该类时,toEntity 为NULL,并且我不知道如何正确测试它。
@RunWith(MockitoJUnitRunner.class)
public class MyTest {
@InjectMocks
private MyService _classUnderTest;
@Mock
private MyEntityTransform myEntityTransform
@Before
public void setUp() {
Mockito.when(this.myEntityTransform.toEntity.apply(Mockito.anyObject())).thenReturn(...);
}
}
当我运行 JUNIT 测试时,Mockito 给出错误:
java.lang.NullPointerException org.mockito.exceptions.misusing.InvalidUseOfMatchersException: Misplaced argument matcher detected here:
-> at com.example.MyTest.setUp(MyTest.java:38)
You cannot use argument matchers outside of verification or stubbing. Examples of correct usage of argument matchers: when(mock.get(anyInt())).thenReturn(null); doThrow(new RuntimeException()).when(mock).someVoidMethod(anyObject()); verify(mock).someMethod(contains("foo"))
Also, this error might show up because you use argument matchers with methods that cannot be mocked. Following methods cannot be stubbed/verified: final/private/equals()/hashCode(). Mocking methods declared on non-public parent classes is not supported.
你有什么建议吗?
最佳答案
您正在使用公共(public)字段,这不是一个好主意。但无论如何,您想要模拟的是函数,而不是 MyEntityTransform 的实例。所以你需要类似的东西
@InjectMocks
private MyService _classUnderTest;
@Mock // or @Spy
private MyEntityTransform myEntityTransform;
@Before
public void prepare() {
myEntityTransform.toEntity = mock(Function.class);
}
但坦率地说,我不会使用 Function 类型的公共(public)字段。相反,我会使用公共(public)方法:
public class MyEntityTransform {
public MyEntity toEntity(MyDTO record) {
return new MyEntity();
}
}
然后你可以模拟 MyEntityTransform 并使其 toEntity 方法返回你想要的内容。如果您需要传递一个函数来执行该方法的操作,请使用方法引用:
collection.stream().map(myEntityTranform::toEntity)
关于java - 如何使用 Mockito JUNIT java.util.Function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40685523/