启用 webmvc 时,基于 Spring Java 的配置和 JUnit 不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14615629/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 16:50:09  来源:igfitidea点击:

Spring Java based config and JUnit does not work when webmvc is enabled

javaspringmodel-view-controllerconfigurationjunit

提问by MickJ

I have started with a new Spring 3.2.0.RELEASEbased application and I really wanted to do away with XML configuration since its a new project but I have run into a wall when it comes to writing Junittests.

我已经开始使用一个新的基于Spring 3.2.0.RELEASE的应用程序,我真的很想取消 XML 配置,因为它是一个新项目,但在编写Junit测试时遇到了障碍

Here is The java config (WebConfig.java): package com.myapp.config;

这是 java 配置 ( WebConfig.java): package com.myapp.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

@Configuration
@EnableWebMvc
@ComponentScan("com.myapp.controllers")
public class WebConfig{
     @Bean
     public InternalResourceViewResolver configureInternalResourceViewResolver() {
         InternalResourceViewResolver resolver = new InternalResourceViewResolver();
         resolver.setPrefix("/WEB-INF/views/");
         resolver.setSuffix(".jsp");
         return resolver;
     }
}

This is the test class:

这是测试类

package com.myapp.test.integration;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;

import com.myapp.config.WebConfig;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes={ WebConfig.class})
@WebAppConfiguration
public class HomeControllerTest {

    @Test
    public void testController(){
        System.out.println("Executing test");
    }   

}

When I try to runthe test I get the following(I have enabled debugto get more info):

当我尝试运行测试时,我得到以下信息(我已启用调试以获取更多信息):

DEBUG: org.springframework.test.context.junit4.SpringJUnit4ClassRunner - SpringJUnit4ClassRunner constructor called with [class com.myapp.test.integration.HomeControllerTest].
DEBUG: org.springframework.test.context.support.AbstractDelegatingSmartContextLoader - Delegating to AnnotationConfigWebContextLoader to process context configuration [ContextConfigurationAttributes@252d252d declaringClass = 'com.myapp.test.integration.HomeControllerTest', locations = '{}', classes = '{class com.myapp.config.WebConfig}', inheritLocations = true, initializers = '{}', inheritInitializers = true, contextLoaderClass = 'org.springframework.test.context.ContextLoader'].
DEBUG: org.springframework.test.context.ContextLoaderUtils - Could not find an 'annotation declaring class' for annotation type [org.springframework.test.context.ActiveProfiles] and class [com.myapp.test.integration.HomeControllerTest]
DEBUG: org.springframework.test.context.TestContextManager - @TestExecutionListeners is not present for class [class com.myapp.test.integration.HomeControllerTest]: using defaults.
DEBUG: org.springframework.test.context.TestContextManager - Could not instantiate default TestExecutionListener class [org.springframework.test.context.transaction.TransactionalTestExecutionListener]. Specify custom listener classes or make the default listener classes available.
DEBUG: org.springframework.test.annotation.ProfileValueUtils - Retrieved @ProfileValueSourceConfiguration [null] for test class [com.myapp.test.integration.HomeControllerTest]
DEBUG: org.springframework.test.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [com.myapp.test.integration.HomeControllerTest]
DEBUG: org.springframework.test.annotation.ProfileValueUtils - Retrieved @ProfileValueSourceConfiguration [null] for test class [com.myapp.test.integration.HomeControllerTest]
DEBUG: org.springframework.test.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [com.myapp.test.integration.HomeControllerTest]
DEBUG: org.springframework.test.annotation.ProfileValueUtils - Retrieved @ProfileValueSourceConfiguration [null] for test class [com.myapp.test.integration.HomeControllerTest]
DEBUG: org.springframework.test.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [com.myapp.test.integration.HomeControllerTest]
DEBUG: org.springframework.test.annotation.ProfileValueUtils - Retrieved @ProfileValueSourceConfiguration [null] for test class [com.myapp.test.integration.HomeControllerTest]
DEBUG: org.springframework.test.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [com.myapp.test.integration.HomeControllerTest]
DEBUG: org.springframework.test.annotation.ProfileValueUtils - Retrieved @ProfileValueSourceConfiguration [null] for test class [com.myapp.test.integration.HomeControllerTest]
DEBUG: org.springframework.test.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [com.myapp.test.integration.HomeControllerTest]
DEBUG: org.springframework.test.annotation.ProfileValueUtils - Retrieved @ProfileValueSourceConfiguration [null] for test class [com.myapp.test.integration.HomeControllerTest]
DEBUG: org.springframework.test.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [com.myapp.test.integration.HomeControllerTest]
DEBUG: org.springframework.test.context.support.AbstractDelegatingSmartContextLoader - Delegating to AnnotationConfigWebContextLoader to load context from [WebMergedContextConfiguration@a580a58 testClass = HomeControllerTest, locations = '{}', classes = '{class com.myapp.config.WebConfig}', contextInitializerClasses = '[]', activeProfiles = '{}', resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.test.context.web.WebDelegatingSmartContextLoader'].
DEBUG: org.springframework.test.context.web.AbstractGenericWebContextLoader - Loading WebApplicationContext for merged context configuration [WebMergedContextConfiguration@a580a58 testClass = HomeControllerTest, locations = '{}', classes = '{class com.myapp.config.WebConfig}', contextInitializerClasses = '[]', activeProfiles = '{}', resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.test.context.web.WebDelegatingSmartContextLoader'].
DEBUG: org.springframework.test.context.web.AnnotationConfigWebContextLoader - Registering annotated classes: {class com.myapp.config.WebConfig}
INFO : org.springframework.web.context.support.GenericWebApplicationContext - Refreshing org.springframework.web.context.support.GenericWebApplicationContext@5cf15cf1: startup date [Wed Jan 30 17:42:16 EST 2013]; root of context hierarchy
INFO : org.springframework.context.annotation.ClassPathBeanDefinitionScanner - JSR-250 'javax.annotation.ManagedBean' found and supported for component scanning
INFO : org.springframework.context.annotation.ClassPathBeanDefinitionScanner - JSR-330 'javax.inject.Named' annotation found and supported for component scanning
INFO : org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor - JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
DEBUG: org.springframework.ui.context.support.UiApplicationContextUtils - Unable to locate ThemeSource with name 'themeSource': using default [org.springframework.ui.context.support.ResourceBundleThemeSource@7a487a48]
INFO : org.springframework.beans.factory.support.DefaultListableBeanFactory - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@61266126: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,webConfig,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor,homeController,org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration,requestMappingHandlerMapping,mvcContentNegotiationManager,viewControllerHandlerMapping,beanNameHandlerMapping,resourceHandlerMapping,defaultServletHandlerMapping,requestMappingHandlerAdapter,mvcConversionService,mvcValidator,httpRequestHandlerAdapter,simpleControllerHandlerAdapter,handlerExceptionResolver,configureInternalResourceViewResolver]; root of factory hierarchy
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.String com.myapp.controllers.HomeController.home(java.util.Locale,org.springframework.ui.Model)
DEBUG: org.springframework.jndi.JndiTemplate - Looking up JNDI object with name [java:comp/env/spring.liveBeansView.mbeanDomain]
Jan 30, 2013 5:42:17 PM null null
SEVERE: javaAccessorNotSet
DEBUG: org.springframework.jndi.JndiLocatorDelegate - Converted JNDI name [java:comp/env/spring.liveBeansView.mbeanDomain] not found - trying original name [spring.liveBeansView.mbeanDomain]. javax.naming.ConfigurationException: Name space accessor for the java: name space has not been set. Possible cause is that the user is specifying a java: URL name in a JNDI Context method call but is not running in a J2EE client or server environment.
DEBUG: org.springframework.jndi.JndiTemplate - Looking up JNDI object with name [spring.liveBeansView.mbeanDomain]
DEBUG: org.springframework.test.context.support.DirtiesContextTestExecutionListener - After test class: context [[TestContext@12a312a3 testClass = HomeControllerTest, testInstance = [null], testMethod = [null], testException = [null], mergedContextConfiguration = [WebMergedContextConfiguration@a580a58 testClass = HomeControllerTest, locations = '{}', classes = '{class com.myapp.config.WebConfig}', contextInitializerClasses = '[]', activeProfiles = '{}', resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.test.context.web.WebDelegatingSmartContextLoader']]], dirtiesContext [false].

回答by ramirezag

You forgot to set the active profile. Here's a running sample test. Home Controller:

您忘记设置活动配置文件。这是一个正在运行的示例测试。家庭控制器:

package com.myapp.test.integration;

import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 *
 */
@Controller
@Profile("cloudx")
public class HomeController {
    @RequestMapping("/test")
    public String test() {
        return "test";
    }
}

WebConfig:

网络配置:

package com.myapp.test;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

@Configuration
@EnableWebMvc
@ComponentScan("com.myapp.test")
public class WebConfig {
    @Bean
    public InternalResourceViewResolver configureInternalResourceViewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".jsp");
        return resolver;
    }
}

HomeControllerTest:

家庭控制器测试:

package com.myapp.test;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = WebConfig.class)
@WebAppConfiguration
@ActiveProfiles("cloudx")
public class HomeControllerTest {
    @Autowired
    protected WebApplicationContext wac;
    protected MockMvc mockMvc;

    @Before
    public final void onSetup() throws Exception {
        mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
    }

    @Test
    public void test() throws Exception {
        MvcResult result = mockMvc.perform(get("/test")).andExpect(status().isOk()).andReturn();
        System.out.println(result.getResponse().getContentAsString());
    }

}