9677

WebMvcTest in Spring Boot

I have a basic SpringBoot app., embedded Tomcat, Thymeleaf template engine, and package as an executable JAR file.

I have this class:

@Service public class I18NService { /** The application logger */ private static final Logger LOG = LoggerFactory.getLogger(I18NService.class); @Autowired private MessageSource messageSource; ... }

this controller

@Controller public class ForgotMyPasswordController extends TdkController { @Autowired private I18NService i18NService; @Autowired private EmailService emailService; ... }

Start the application works fine, This Test also is working perfectly

public class ForgotMyPasswordControllerTests { private ForgotMyPasswordController controller; @Before public void setUp() throws Exception { controller = new ForgotMyPasswordController(); } @Test public void testHandleListRequest() { assertEquals("forgotmypassword/emailForm", controller.forgotPasswordGet()); } }

but when I run this one :

@RunWith(SpringRunner.class) @WebAppConfiguration @WebMvcTest public class MockMvcTests { // Pull in the application context created by @ContextConfiguration @Autowired private WebApplicationContext wac; private MockMvc mockMvc; @Before public void setup() { // Setup MockMVC to use our Spring Configuration this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); } @Test public void getDeviceEventsTest() throws Exception { this.mockMvc .perform(get("/forgotmypassword") // .accept(MediaType.parseMediaType("text/html;charset=UTF-8"))) .andExpect(status().isOk()) // .andExpect(model().size(0)); // } }

I got this error:

16486 [main] ERROR o.s.test.context.TestContextManager - Caught exception while allowing TestExecutionListener [org.springframework.test.context.web.ServletTestExecutionListener@5876a9af] to prepare test instance [com.tdk.iot.web.controllers.MockMvcTests@6b1e7ad3] java.lang.IllegalStateException: Failed to load ApplicationContext at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124) at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:83) at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:189) at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:131) at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:230) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:228) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:287) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:289) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:247) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70) at org.junit.runners.ParentRunner.run(ParentRunner.java:363) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192) Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'forgotMyPasswordController': Unsatisfied dependency expressed through field 'i18NService'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.tdk.web.i18n.I18NService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:588) at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:366) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1264) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542) at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:737) at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:370) at org.springframework.boot.SpringApplication.run(SpringApplication.java:314) at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:120) at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:98) at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:116) ... 25 common frames omitted Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.tdk.web.i18n.I18NService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1486) at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1104) at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:585) ... 43 common frames omitted

Answer1:

The whole point of WebMvcTest is to only load the MVC components. Other components must be mocked. Read the documentation:

To test Spring MVC controllers are working as expected you can use the @WebMvcTest annotation. @WebMvcTest will auto-configure the Spring MVC infrastructure and limit scanned beans to @Controller, @ControllerAdvice, @JsonComponent, Filter, WebMvcConfigurer and HandlerMethodArgumentResolver. Regular @Component beans will not be scanned when using this annotation.

Often @WebMvcTest will be limited to a single controller and used in combination with @MockBean to provide mock implementations for required collaborators.

Recommend

  • Spring HttpMessageNotReadableException
  • 404 response on simple RESTeasy example with Tomcat
  • File download through ajax
  • HowTo for newbie: Managing currency in iPhone app
  • How to insert alt tags dynamically in jsp
  • Is it possible to use an http url as your source location of a Source Filter in DirectShow .Net?
  • Unit Testing Spring MVC Controller that returns PagedResources
  • Detecting single one-bit streams within an integer
  • How can I reset dropdown data if modal closed on vue component?
  • Is it better to have roles as a column on my users table, or do it through join tables (Roles &
  • How to merge keras sequential models with same input?
  • Returning the auto incrementing value after an insert using slick
  • Django model for a Postgres view
  • Activation Function choice for Neural network
  • Clear activity stack before launching another activity
  • How to getText() from the input field of an angularjs Application
  • Angular2 Response for preflight is invalid (redirect) from some GET requests
  • Combining two different ActiveRecord collections into one
  • Angularjs pass function from Controller to Directive (or call controller function from directive) -
  • How do I configure context broker accept post requests from my remote sensor?
  • Django invalid literal for int() with base 10
  • Eloquent update method change created_at timestamp
  • Transactional Create with Validation in ServiceStack Redis Client
  • Hardware Accelerated Image Scaling in windows using C++
  • The plugin 'org.apache.maven.plugins:maven-jboss-as-plugin' does not exist or no valid ver
  • Validaiting emails with Net.Mail MailAddress
  • MySQL WHERE-condition in procedure ignored
  • jquery mobile loadPage not working
  • Web-crawler for facebook in python
  • How to get icons for entities from eclipse?
  • trying to dynamically update Highchart column chart but series undefined
  • Proper way to use connect-multiparty with express.js?
  • Load html files in TinyMce
  • Suggestions to manage Login/Logout transitions
  • MATLAB: Piecewise function in curve fitting toolbox using fittype
  • JaxB to read class hierarchy
  • Why is Django giving me: 'first_name' is an invalid keyword argument for this function?
  • Binding checkboxes to object values in AngularJs
  • How can I use `wmic` in a Windows PE script?
  • java string with new operator and a literal