I am using mockito with cucumber . I have a code in step def which looks like this :
@Mock
private SystemsConfig systemsConfig;
@And("The login to mySytem is executed successfully")
public void loginToMySystem() {
Mockito.when(systemsConfig.getUrl()).thenReturn(MyUnitMocks.baseUrl);
}
When debugging I see that systemsConfig is coming up as null though I have mocked it . The same works perfectly using junit . Why so ? How can I achieve this with mockito and cucumber ?
CodePudding user response:
It doesn't work because there is no such thing as magic. There must be something that connects Mockito to JUnit so it knows when to create mocks.
When you are using JUnit you are also using either a Mockito Junit extension, Mockito JUnit runner, a framework like Spring or something else that effectively invokes:
MockitoAnnotations.initMocks(this);
There is no such extension for Cucumber. So when using Cucumber you have to do this in a before hook.
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
}
You can find a more update explanation in the Java doc for @Mock
.
https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mock.html