How to use Mockito with JUnit5
There are different ways to use Mockito - I'll go through them one by one.
Manually
Creating mocks manually with Mockito::mock
works regardless of the JUnit version (or test framework for that matter).
Annotation Based
Using the @Mock-annotation and the corresponding call to MockitoAnnotations::initMocks
to create mocks works regardless of the JUnit version (or test framework for that matter but Java 9 could interfere here, depending on whether the test code ends up in a module or not).
Mockito Extension
JUnit 5 has a powerful extension model and Mockito recently published one under the group / artifact ID org.mockito : mockito-junit-jupiter.
You can apply the extension by adding @ExtendWith(MockitoExtension.class)
to the test class and annotating mocked fields with @Mock
. From MockitoExtension
's JavaDoc:
@ExtendWith(MockitoExtension.class)
public class ExampleTest {
@Mock
private List list;
@Test
public void shouldDoSomething() {
list.add(100);
}
}
The MockitoExtension documentation describes other ways to instantiate mocks, for example with constructor injection (if you rpefer final fields in test classes).
No Rules, No Runners
JUnit 4 rules and runners don't work in JUnit 5, so the MockitoRule
and the Mockito runner can not be used.
How to use mockito 3.0 with JUnit 5?
The MockitoExtension
is published in the mockito-junit-jupiter
artifact.
You can add a dependency on it as follows.
Maven
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-junit-jupiter</artifactId>
<version>2.27.0</version>
<scope>test</scope>
</dependency>
Gradle
testCompile 'org.mockito:mockito-junit-jupiter:2.27.0'
Further Resources
- https://github.com/mockito/mockito/issues/1517#issuecomment-429621891
- https://search.maven.org/artifact/org.mockito/mockito-junit-jupiter/2.27.0/jar
Related Topics
Simple Sso - Using Custom Authentication - Cas or Some Oauth or Openid Server
Hbase Client Connectionloss for /Hbase Error
Is There an Advantage to Running Jruby If You Don't Know Any Java
Aes Cbc Pkcs5Padding Java to Ruby
Java Object Analogue to R Data.Frame
Libjvm.So: Cannot Open Shared Object File: No Such File or Directory
Java Equivalent to JavaScript's Encodeuricomponent That Produces Identical Output
Alternative to Jzebra/Qz Java Raw Print Plugin After Npapi Being Dropped on Chrome Browser
Calling a Java Servlet from JavaScript
Fileuriexposedexception in Android
Android Debugging Inetaddress.Isreachable
Detecting Device Type in a Web Application
Java.Lang.Classnotfoundexception: Org.Postgresql.Driver, Android
Read Data from SQLite Where Column Name Contains Spaces
No Resource Identifier Found for Attribute 'Layout_Behavior' in Package