In a Spring application sometimes we need to mock certain beans. For example, we may have a remote service whose instance cannot be created within tests.
Spring Boot provides @MockBean annotation that can be used to define a Mockito mock for a bean inside our ApplicationContext , that means the mock declared in test class (by using @MockBean) will be injected as a bean within the application.
Example
Example Spring Boot application
package com.logicbig.example;
public interface HelloService {
String getMessage();
}
package com.logicbig.example;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class MyHelloProcessor {
@Autowired
private HelloService helloService;
public String getMessage() {
return helloService.getMessage();
}
}
Using @MockBean in tests
package com.logicbig.example;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class MyHelloProcessorTest {
@Autowired
private MyHelloProcessor myHelloProcessor;
@MockBean
private HelloService helloService;
@Test
public void testSayHi() {
Mockito.when(helloService.getMessage()).thenReturn("test message.");
String message = myHelloProcessor.getMessage();
Assert.assertEquals(message, "test message.");
}
}
D:\spring-boot-using-annotation-mockbean>mvn test -Dtest=MyHelloProcessorTest.java [INFO] Scanning for projects... [INFO] [INFO] -----< com.logicbig.example:spring-boot-using-annotation-mockbean >----- [INFO] Building spring-boot-using-annotation-mockbean 1.0-SNAPSHOT [INFO] --------------------------------[ jar ]--------------------------------- [INFO] [INFO] --- maven-resources-plugin:3.1.0:resources (default-resources) @ spring-boot-using-annotation-mockbean --- [INFO] Using 'UTF-8' encoding to copy filtered resources. [INFO] [INFO] --- maven-compiler-plugin:3.8.1:compile (default-compile) @ spring-boot-using-annotation-mockbean --- [INFO] Nothing to compile - all classes are up to date [INFO] [INFO] --- maven-resources-plugin:3.1.0:testResources (default-testResources) @ spring-boot-using-annotation-mockbean --- [INFO] Using 'UTF-8' encoding to copy filtered resources. [INFO] [INFO] --- maven-compiler-plugin:3.8.1:testCompile (default-testCompile) @ spring-boot-using-annotation-mockbean --- [INFO] Nothing to compile - all classes are up to date [INFO] [INFO] --- maven-surefire-plugin:2.22.2:test (default-test) @ spring-boot-using-annotation-mockbean --- [INFO] [INFO] ------------------------------------------------------- [INFO] T E S T S [INFO] ------------------------------------------------------- 01:07:10.945 [main] DEBUG org.springframework.test.context.junit4.SpringJUnit4ClassRunner - SpringJUnit4ClassRunner constructor called with [class com.logicbig.example.MyHelloProcessorTest] 01:07:10.949 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating CacheAwareContextLoaderDelegate from class [org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate] 01:07:10.956 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating BootstrapContext using constructor [public org.springframework.test.context.support.DefaultBootstrapContext(java.lang.Class,org.springframework.test.context.CacheAwareContextLoaderDelegate)] 01:07:10.979 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating TestContextBootstrapper for test class [com.logicbig.example.MyHelloProcessorTest] from class [org.springframework.boot.test.context.SpringBootTestContextBootstrapper] 01:07:10.991 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Neither @ContextConfiguration nor @ContextHierarchy found for test class [com.logicbig.example.MyHelloProcessorTest], using SpringBootContextLoader 01:07:10.995 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [com.logicbig.example.MyHelloProcessorTest]: class path resource [com/logicbig/example/MyHelloProcessorTest-context.xml] does not exist 01:07:10.995 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [com.logicbig.example.MyHelloProcessorTest]: class path resource [com/logicbig/example/MyHelloProcessorTestContext.groovy] does not exist 01:07:10.995 [main] INFO org.springframework.test.context.support.AbstractContextLoader - Could not detect default resource locations for test class [com.logicbig.example.MyHelloProcessorTest]: no resource found for suffixes {-context.xml, Context.groovy}. 01:07:10.996 [main] INFO org.springframework.test.context.support.AnnotationConfigContextLoaderUtils - Could not detect default configuration classes for test class [com.logicbig.example.MyHelloProcessorTest]: MyHelloProcessorTest does not declare any static, non-private, non-final, nested classes annotated with @Configuration. 01:07:11.038 [main] DEBUG org.springframework.test.context.support.ActiveProfilesUtils - Could not find an 'annotation declaring class' for annotation type [org.springframework.test.context.ActiveProfiles] and class [com.logicbig.example.MyHelloProcessorTest] 01:07:11.089 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Found @SpringBootConfiguration com.logicbig.example.AppMain for test class com.logicbig.example.MyHelloProcessorTest 01:07:11.175 [main] DEBUG org.springframework.boot.test.context.SpringBootTestContextBootstrapper - @TestExecutionListeners is not present for class [com.logicbig.example.MyHelloProcessorTest]: using defaults. 01:07:11.176 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener, org.springframework.boot.test.autoconfigure.webservices.client.MockWebServiceServerTestExecutionListener, org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener, org.springframework.test.context.event.EventPublishingTestExecutionListener] 01:07:11.185 [main] DEBUG org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Skipping candidate TestExecutionListener [org.springframework.test.context.transaction.TransactionalTestExecutionListener] due to a missing dependency. Specify custom listener classes or make the default listener classes and their required dependencies available. Offending class: [org/springframework/transaction/interceptor/TransactionAttributeSource] 01:07:11.185 [main] DEBUG org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Skipping candidate TestExecutionListener [org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener] due to a missing dependency. Specify custom listener classes or make the default listener classes and their required dependencies available. Offending class: [org/springframework/transaction/interceptor/TransactionAttribute] 01:07:11.185 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Using TestExecutionListeners: [org.springframework.test.context.web.ServletTestExecutionListener@1130520d, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@5f77d0f9, org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener@463fd068, org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener@895e367, org.springframework.test.context.support.DirtiesContextTestExecutionListener@1b266842, org.springframework.test.context.event.EventPublishingTestExecutionListener@7a3793c7, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener@42b3b079, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener@651aed93, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener@4dd6fd0a, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener@bb9e6dc, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener@5456afaa, org.springframework.boot.test.autoconfigure.webservices.client.MockWebServiceServerTestExecutionListener@6692b6c6] 01:07:11.188 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved @ProfileValueSourceConfiguration [null] for test class [com.logicbig.example.MyHelloProcessorTest] 01:07:11.189 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [com.logicbig.example.MyHelloProcessorTest] 01:07:11.190 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved @ProfileValueSourceConfiguration [null] for test class [com.logicbig.example.MyHelloProcessorTest] 01:07:11.191 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [com.logicbig.example.MyHelloProcessorTest] 01:07:11.194 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved @ProfileValueSourceConfiguration [null] for test class [com.logicbig.example.MyHelloProcessorTest] 01:07:11.194 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [com.logicbig.example.MyHelloProcessorTest] 01:07:11.226 [main] DEBUG org.springframework.test.context.junit4.SpringJUnit4ClassRunner - SpringJUnit4ClassRunner constructor called with [class com.logicbig.example.MyHelloProcessorTest] 01:07:11.226 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating CacheAwareContextLoaderDelegate from class [org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate] 01:07:11.226 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating BootstrapContext using constructor [public org.springframework.test.context.support.DefaultBootstrapContext(java.lang.Class,org.springframework.test.context.CacheAwareContextLoaderDelegate)] 01:07:11.227 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating TestContextBootstrapper for test class [com.logicbig.example.MyHelloProcessorTest] from class [org.springframework.boot.test.context.SpringBootTestContextBootstrapper] 01:07:11.229 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Neither @ContextConfiguration nor @ContextHierarchy found for test class [com.logicbig.example.MyHelloProcessorTest], using SpringBootContextLoader 01:07:11.230 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [com.logicbig.example.MyHelloProcessorTest]: class path resource [com/logicbig/example/MyHelloProcessorTest-context.xml] does not exist 01:07:11.230 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [com.logicbig.example.MyHelloProcessorTest]: class path resource [com/logicbig/example/MyHelloProcessorTestContext.groovy] does not exist 01:07:11.230 [main] INFO org.springframework.test.context.support.AbstractContextLoader - Could not detect default resource locations for test class [com.logicbig.example.MyHelloProcessorTest]: no resource found for suffixes {-context.xml, Context.groovy}. 01:07:11.230 [main] INFO org.springframework.test.context.support.AnnotationConfigContextLoaderUtils - Could not detect default configuration classes for test class [com.logicbig.example.MyHelloProcessorTest]: MyHelloProcessorTest does not declare any static, non-private, non-final, nested classes annotated with @Configuration. 01:07:11.233 [main] DEBUG org.springframework.test.context.support.ActiveProfilesUtils - Could not find an 'annotation declaring class' for annotation type [org.springframework.test.context.ActiveProfiles] and class [com.logicbig.example.MyHelloProcessorTest] 01:07:11.234 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Found @SpringBootConfiguration com.logicbig.example.AppMain for test class com.logicbig.example.MyHelloProcessorTest 01:07:11.237 [main] DEBUG org.springframework.boot.test.context.SpringBootTestContextBootstrapper - @TestExecutionListeners is not present for class [com.logicbig.example.MyHelloProcessorTest]: using defaults. 01:07:11.238 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener, org.springframework.boot.test.autoconfigure.webservices.client.MockWebServiceServerTestExecutionListener, org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener, org.springframework.test.context.event.EventPublishingTestExecutionListener] 01:07:11.242 [main] DEBUG org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Skipping candidate TestExecutionListener [org.springframework.test.context.transaction.TransactionalTestExecutionListener] due to a missing dependency. Specify custom listener classes or make the default listener classes and their required dependencies available. Offending class: [org/springframework/transaction/interceptor/TransactionAttributeSource] 01:07:11.243 [main] DEBUG org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Skipping candidate TestExecutionListener [org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener] due to a missing dependency. Specify custom listener classes or make the default listener classes and their required dependencies available. Offending class: [org/springframework/transaction/interceptor/TransactionAttribute] 01:07:11.244 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Using TestExecutionListeners: [org.springframework.test.context.web.ServletTestExecutionListener@19e7a160, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@662706a7, org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener@45a4b042, org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener@16b2bb0c, org.springframework.test.context.support.DirtiesContextTestExecutionListener@327af41b, org.springframework.test.context.event.EventPublishingTestExecutionListener@6cb6decd, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener@c7045b9, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener@f99f5e0, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener@6aa61224, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener@30bce90b, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener@3e6f3f28, org.springframework.boot.test.autoconfigure.webservices.client.MockWebServiceServerTestExecutionListener@7e19ebf0] 01:07:11.244 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved @ProfileValueSourceConfiguration [null] for test class [com.logicbig.example.MyHelloProcessorTest] 01:07:11.244 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [com.logicbig.example.MyHelloProcessorTest] 01:07:11.245 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved @ProfileValueSourceConfiguration [null] for test class [com.logicbig.example.MyHelloProcessorTest] 01:07:11.245 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [com.logicbig.example.MyHelloProcessorTest] 01:07:11.245 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved @ProfileValueSourceConfiguration [null] for test class [com.logicbig.example.MyHelloProcessorTest] 01:07:11.245 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [com.logicbig.example.MyHelloProcessorTest] 01:07:11.293 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved @ProfileValueSourceConfiguration [null] for test class [com.logicbig.example.MyHelloProcessorTest] 01:07:11.293 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [com.logicbig.example.MyHelloProcessorTest] [INFO] Running com.logicbig.example.MyHelloProcessorTest 01:07:11.296 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved @ProfileValueSourceConfiguration [null] for test class [com.logicbig.example.MyHelloProcessorTest] 01:07:11.296 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [com.logicbig.example.MyHelloProcessorTest] 01:07:11.296 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved @ProfileValueSourceConfiguration [null] for test class [com.logicbig.example.MyHelloProcessorTest] 01:07:11.297 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [com.logicbig.example.MyHelloProcessorTest] 01:07:11.304 [main] DEBUG org.springframework.test.context.support.AbstractDirtiesContextTestExecutionListener - Before test class: context [DefaultTestContext@76a2ddf3 testClass = MyHelloProcessorTest, testInstance = [null], testMethod = [null], testException = [null], mergedContextConfiguration = [WebMergedContextConfiguration@524f3b3a testClass = MyHelloProcessorTest, locations = '{}', classes = '{class com.logicbig.example.AppMain}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@7c9d8e2, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@2002fc1d, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@48366845, org.springframework.boot.test.web.client.TestRestTemplateContextCustomizer@10aa41f2, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@610f7aa, org.springframework.boot.test.context.SpringBootTestArgs@1], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]], attributes = map['org.springframework.test.context.web.ServletTestExecutionListener.activateListener' -> true]], class annotated with @DirtiesContext [false] with mode [null]. 01:07:11.308 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved @ProfileValueSourceConfiguration [null] for test class [com.logicbig.example.MyHelloProcessorTest] 01:07:11.308 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [com.logicbig.example.MyHelloProcessorTest] 01:07:11.331 [main] DEBUG org.springframework.test.context.support.TestPropertySourceUtils - Adding inlined properties to environment: {spring.jmx.enabled=false, org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}
. ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v2.3.3.RELEASE)
2020-09-01 01:07:11.507 INFO 10932 --- [ main] c.logicbig.example.MyHelloProcessorTest : No active profile set, falling back to default profiles: default 2020-09-01 01:07:12.793 INFO 10932 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor' 2020-09-01 01:07:13.055 INFO 10932 --- [ main] c.logicbig.example.MyHelloProcessorTest : Started MyHelloProcessorTest in 1.717 seconds (JVM running for 2.539) [INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.799 s - in com.logicbig.example.MyHelloProcessorTest 2020-09-01 01:07:13.112 INFO 10932 --- [extShutdownHook] o.s.s.concurrent.ThreadPoolTaskExecutor : Shutting down ExecutorService 'applicationTaskExecutor' [INFO] [INFO] Results: [INFO] [INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0 [INFO] [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------------------ [INFO] Total time: 4.657 s [INFO] Finished at: 2020-09-01T01:07:13-05:00 [INFO] ------------------------------------------------------------------------
Example ProjectDependencies and Technologies Used: - Spring Boot 2.3.3.RELEASE
- spring-boot-starter-web : Starter for building web, including RESTful, applications using Spring MVC. Uses Tomcat as the default embedded container.
- spring-boot-starter-test : Starter for testing Spring Boot applications with libraries including JUnit, Hamcrest and Mockito.
- JDK 1.8
- Maven 3.5.4
|
|