gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:10:19 28 4
gpt4 key购买 nike

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

这里是java配置(WebConfig.java): 包 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;
}
}

这是测试类:

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");
}

}

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

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].

最佳答案

您忘记设置 Activity 配置文件。这是一个正在运行的示例测试。家庭 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";
}
}

网络配置:

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;
}
}

家庭 Controller 测试:

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());
}

}

关于java - 启用 webmvc 时,基于 Spring Java 的配置和 JUnit 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14615629/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com