Home > OS >  How to use mockito-inline with Spring-Boot?
How to use mockito-inline with Spring-Boot?

Time:04-08

Context: We are using Junit 5, Spring-Boot 2.6.3 Spring-Boot comes with its dependency on mockito-core

Problem I am looking to create a mock for a static method. Mockito provides a library (mockito-inline) that allows mocking static methods, however, it works when mockito-core is not directly in dependency. Mockito-inline downloads the compatible mockito-core when required.
(ref: https://frontbackend.com/java/how-to-mock-static-methods-with-mockito)

Possible Solutions

  1. Remove mockito-core from spring-boot - Please help by suggesting how can it be done, without impacting the same dependency being added by Mockito-inline?
  2. There is a problem with my understanding - If this is the case, kindly help me understand it better, with probably an example of using Mockito with Spring-boot to mock static method

CodePudding user response:

mockito-core is pulled in by spring-boot-starter-test. Just exclude it and add mockito-inline as a test dependency.

CodePudding user response:

No additional dependency should be required. Mockito.mockStatic is part of mockito core. As far as I remeber you just have to add the file "org.mockito.plugins.MockMaker" in the folder "mockito-extensions" in your test resources root.

However if you really want to exclude the dependency of mockito from spring you can do so by adding an exclusion in your pom.xml dependency. An example of how to explicitly exclude a dependency of a library would look like this.

    <dependency>
        <groupId>jcifs</groupId>
        <artifactId>jcifs</artifactId>
        <version>1.3.17</version>
        <exclusions>
            <exclusion>
                <groupId>javax.servlet</groupId>
                <artifactId>servlet-api</artifactId>
            </exclusion>
        </exclusions>
   </dependency>

Also be really carefull with using mockStatic. Always call close in the end or otherwise the staticMock will stay active in the Thread (across multiple unit tests).

Creates a thread-local mock controller for all static methods of the given class or interface. The returned object's MockedStatic.close() method must be called upon completing the test or the mock will remain active on the current thread. Note: We recommend against mocking static methods of classes in the standard library or classes used by custom class loaders used to executed the block with the mocked class. A mock maker might forbid mocking static methods of know classes that are known to cause problems. Also, if a static method is a JVM-intrinsic, it cannot typically be mocked even if not explicitly forbidden. See examples in javadoc for Mockito class Params: classToMock – class or interface of which static mocks should be mocked. defaultAnswer – the default answer when invoking static methods. Returns: mock controller

  • Related