Common questions Answer: How to solve common errors in Mockito Groovy Support framework
How to solve common errors in Mockito Groovy Support framework
Mockito Groovy Support is an extension library for using the Mockito framework in the Groovy test.However, some common errors occur when using Mockito Groovy Support.Here are some common problems and solutions:
1. "groovy.lang.MissingMethodException: No signature of method"错误
This error is usually because Mockito cannot find the signature of the method.One way to solve this problem is to create a dynamic Groovy class in the test using the `Stubfor '.For example:
groovy
def mockedClass = new StubFor(MyClass)
mockedClass.Demand.somemethod {params-> // Definition method logic}
def myInstance = mockedClass.proxyInstance()
In this way, you can use the `MyInstance` to call the` Somethod` method without reporting an error.
2. "Too Few Invacatings" or "TOO MANY Invacatings" error
These errors usually occur when the number of verification methods calls.You can use the number of times to specify the method of `mockito.times` method.For example, if you want to verify that one method is called twice, you can use the following code:
groovy
verify(mockObject, times(2)).someMethod()
3. "Final Method does not support mock" error
Mockito does not support the Mock method for the final method.However, you can use other rotary libraries such as `` PowerMock` or `jmockit` to simulate the final method.
4. "Field 'xxx' does not support Mock" error
Mockito does not support the Mock of the field (that is, attribute).To solve this problem, you can use the dependencies inject to inject the field into your test class as a dependencies.For example, you can use `@injectmocks` annotations to rely on the test class:
@RunWith(MockitoJUnitRunner.class)
public class MyTest {
@InjectMocks
private MyClass myObject;
@Mock
private SomeDependency dependency;
// ...
}
In this way, you can Mock on the `Dependency` field in` myclass`.
Summary: Mockito Groovy Support may have some common errors in use, but most problems can be solved by correctly using the functions provided by Mockito or converted to other Mock frameworks.In order to avoid errors, it is recommended to carefully read the official documentation of Mockito when writing tests, and test according to the best practice.