I'm using Spring Boot and in a unit test, I'm trying to mock the Files.delete(myFile.toPath())
method.
To do so I'm trying to use the Mockito.mockStatic()
method. But when I try to use it my IDE (IntelliJ IDEA) indicate me that this method does not exist.
I read this article :
https://asolntsev.github.io/en/2020/07/11/mockito-static-methods/
but it didn't help me.
In my POM.xml file there is:
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-inline</artifactId>
<version>3.5.15</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-junit-jupiter</artifactId>
<version>3.5.15</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<version>2.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
Note that I only put test related dependency, this is not my whole POM.xml file
In my test file, I put the following imports:
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit4.SpringRunner;
Again, this is only the test related imports.
A screenshot of what my IDE is displaying:
Do you have any idea why the Mockito.mockStatic()
method can't be resolved ?
When writing tests, we'll often encounter a situation where we need to mock a static method. Previous to version 3.4.0 of Mockito, it wasn't possible to mock static methods directly — only with the help of PowerMockito.
@mstachniuk is it still not possible in mockito? Sorry, something went wrong. Yes, it's still not possible. Sorry, something went wrong. Yes, it's still not possible.
On top of this, another nice side effect is that our tests will still run quite fast since Mockito doesn't need to replace the classloader for every test. In our example, we reiterate this point by checking, before and after our scoped block, that our static method name returns a real value.
Let's go ahead and see how we can mock the name method from our StaticUtils class: As previously mentioned, since Mockito 3.4.0, we can use the Mockito.mockStatic (Class<T> classToMock) method to mock invocations to static method calls.
Make sure you have the following dependency in your pom file
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>3.5.15</version>
<scope>test</scope>
</dependency>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With