I would like to mock the following class:
public class MyRunner {
private String name;
private User user;//not final
public MyRunner(String name, User user) {
this.name = name;
this.user = user
}
//...something complicated in the methods
}
Just like with JMockit
@ExtendWith(MockitoExtension.class)
public class MyRunnerTest {
@Inject
private String name = "sth";
@Inject
private User user;
@Tested
private MyRunner tested;
}
Similarly with Mockito 3,
@ExtendWith(MockitoExtension.class)
public class MyRunnerTest {
@Mock
private String name;
@Mock
private User user;
@InjectMocks
private MyRunner tested;
@Test //from JUnit5
public void testSth() {
//...
}
}
Problem : The injection of the name
string into the MyRunner
during construction would fail due to the fact that String
is a final class. Got error message like:
Cannot mock/spy class java.lang.String
Mockito cannot mock/spy because :
- final class
It is possible to intialize the tested class with new keyword:
@ExtendWith(MockitoExtension.class)
public class MyRunnerTest {
private String name = "sth";
@Mock
private User user;
private MyRunner tested = new MyRunner(name, user);
@Test //from JUnit5
public void testSth() {
//...
}
}
However, the solution above is not as fluent as merely using the annotation
Question : How to inject the final class into the object annotated with @InjectMocks
instead of constructing it with new
keyword explicitly?