gpt4 book ai didi

java - Spring-Test-MVC/MockServletContext - 内容在测试中为空但在 Tomcat 上工作

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:45:33 25 4
gpt4 key购买 nike

我们正在尝试为我们的 Spring-MVC 网络应用设置 Spring-Test-MVC。我们开始使用 freemarker,一切都很好。虽然我们决定反对它,但现在正尝试使用 JSP 来设置它。当测试应用程序部署在 Tomcat 上时,它可以正常工作。当我们运行简单测试时:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader = WebContextLoader.class, locations = { "file:src/main/webapp/WEB-INF/servlet-context.xml" })
public class SkelletonTest {

@Inject
private MockMvc mockMvc;

@Test
public void homeTest() throws Exception {
mockMvc.perform(get("/")).andExpect(status().isOk())
.andExpect(content().type("text/html;charset=ISO-8859-1"))
.andExpect(content().string(containsString("Hello World!")));
}

它说:content type not set 或者如果它被删除,内容将只是空的。然而, Controller 将被调用,因此映射必须有效。

所以这强烈表明 View 没有为我们的测试呈现,但我不知道我可能缺少什么设置。

这是我们的 servlet-context.xml:

<context:component-scan base-package="package.to.controllers" />
<mvc:annotation-driven />

<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="exposeContextBeansAsAttributes" value="true" />
<property name="prefix" value="/views/" />
<property name="suffix" value=".jsp" />
</bean>

WebContextLoader:

public class WebContextLoader extends GenericWebContextLoader {
public WebContextLoader() {
super("src/main/webapp", false);
}
}

GenericWebContextLoader是 spring-test-mvc 的原创。

MockMvc 像这样设置为 Bean:

@Configuration
public class TestConfig {

@Inject
private WebApplicationContext wac;

@Bean
public MockMvc create(){
return (MockMvcBuilders.webApplicationContextSetup(this.wac).build());
}
}

这就是设置。 web.xml 未被测试框架使用,应该无关紧要,因为它之前可以正常工作。

我认为在 servlet 上下文中必须有一个额外的设置。它已加载,我进行了检查,但对于 Tomcat 部署的应用程序来说它很重要,我为前缀和后缀设置的内容将被测试忽略。

不确定错误跟踪会有多大帮助,但这里是:

java.lang.AssertionError: Content type not set
at org.springframework.test.web.AssertionErrors.fail(AssertionErrors.java:35)
at org.springframework.test.web.AssertionErrors.assertTrue(AssertionErrors.java:57)
at org.springframework.test.web.server.result.ContentResultMatchers$1.match(ContentResultMatchers.java:59)
at org.springframework.test.web.server.MockMvc$1.andExpect(MockMvc.java:84)
at our.package.SkelletonTest.homeTest(SkelletonTest.java:30)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:83)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)

测试输出:

2012-06-15 10:41:04 TestContextManager [INFO] @TestExecutionListeners is not present for class [class package.to.test.SkelletonTest]: using defaults.
2012-06-15 10:41:05 XmlBeanDefinitionReader [INFO] Loading XML bean definitions from URL [file:src/main/webapp/WEB-INF/servlet-context.xml]
2012-06-15 10:41:05 ClassPathBeanDefinitionScanner [INFO] JSR-330 'javax.inject.Named' annotation found and supported for component scanning
2012-06-15 10:41:05 GenericWebApplicationContext [INFO] Refreshing org.springframework.web.context.support.GenericWebApplicationContext@158539f: startup date [Fri Jun 15 10:41:05 CEST 2012]; root of context hierarchy
2012-06-15 10:41:05 AutowiredAnnotationBeanPostProcessor [INFO] JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
2012-06-15 10:41:05 DefaultListableBeanFactory [INFO] Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@c64bc2: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,testConfig,freemarkerController,homeController,tableService,org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#0,org.springframework.format.support.FormattingConversionServiceFactoryBean#0,org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter#0,org.springframework.web.servlet.handler.MappedInterceptor#0,org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver#0,org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver#0,org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver#0,org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping,org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter,org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter,viewResolver,org.springframework.context.annotation.ConfigurationClassPostProcessor$ImportAwareBeanPostProcessor#0,create]; root of factory hierarchy
2012-06-15 10:41:05 RequestMappingHandlerMapping [INFO] Mapped "{[/],methods=[],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public org.springframework.web.servlet.ModelAndView package.to.controller.HomeController.index()
2012-06-15 10:41:05 RequestMappingHandlerMapping [INFO] Mapped "{[/test],methods=[],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.String package.to.controller.HomeController.test(org.springframework.ui.Model)
2012-06-15 10:41:06 GenericWebContextLoader$1 [INFO] Initializing Spring FrameworkServlet ''
2012-06-15 10:41:06 TestDispatcherServlet [INFO] FrameworkServlet '': initialization started
2012-06-15 10:41:06 TestDispatcherServlet [INFO] FrameworkServlet '': initialization completed in 32 ms
2012-06-15 10:41:06 GenericWebApplicationContext [INFO] Closing org.springframework.web.context.support.GenericWebApplicationContext@158539f: startup date [Fri Jun 15 10:41:05 CEST 2012]; root of context hierarchy
2012-06-15 10:41:06 DefaultListableBeanFactory [INFO] Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@c64bc2: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,testConfig,freemarkerController,homeController,tableService,org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#0,org.springframework.format.support.FormattingConversionServiceFactoryBean#0,org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter#0,org.springframework.web.servlet.handler.MappedInterceptor#0,org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver#0,org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver#0,org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver#0,org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping,org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter,org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter,viewResolver,org.springframework.context.annotation.ConfigurationClassPostProcessor$ImportAwareBeanPostProcessor#0,create]; root of factory hierarchy

非常感谢任何帮助我找到问题的建议!

顺便说一句:不想再拖下去了,所以我跳过了 pom。我们正在使用 Spring 3.1、spring-test-mvc 1.0.0..BUILD-SNAPSHOT、jsp-ap 2.2、jSTL 1.2,...如果您需要了解更多信息,我会尝试将其上传到某处...


编辑

如果您需要更多信息或为什么不能回答我的问题,请告诉我。真的需要弄清楚,我不知道从哪里开始。因此,也欢迎任何想法或评论。


编辑2

使用具有以下输出的打印方法:

MockHttpServletRequest:
HTTP Method = GET
Request URI = /
Parameters = {}
Headers = {}

Handler:
Type = package.to.controller.HomeController
Method = public org.springframework.web.servlet.ModelAndView package.to.controller.HomeController.index()

Resolved Exception:
Type = null

ModelAndView:
View name = index
View = null
Attribute = welcome
value = Hello World!

FlashMap:

MockHttpServletResponse:
Status = 200
Error message = null
Headers = {}
Content type = null
Body =
Forwarded URL = /views/index.jsp
Redirected URL = null
Cookies = []

这只是更好地说明问题而不是解决方案...


edit3

刚刚发现了以下内容:

JSP 需要一个 servlet 容器。所以看来我无法以这种方式测试我的页面......如果有人知道如何解决这个问题,请告诉我......

最佳答案

@Biju——我很欣赏这个答案,它让我省了点事,我不是想在这里开枪,但我必须说,为了 Spring 团队中可能有动力构建某些东西的任何人的利益更好的是,我发现 MockMVC 几乎是一种琐碎和徒劳的练习。首先,不直接支持 Spring 身份验证。好吧,如果你搜索一下 StackOverflow,你就可以找到一个解决方法。然后我自己发现,如果你在你的 spring 上下文配置中,你可以组成的每条路径都会返回“OK”,即使它应该返回“notFound”。好吧,不管怎样,把它拿出来,让我们再也不提它了。 :) 现在发现 MockMVC 实际上只是 MockMC——没有发生 View 处理。因此,归根结底,该软件的优势在于测试既不包含安全性也不包含 View 的应用程序——这究竟是什么玩具 JSON 应用程序?

这并不是一个真正的答案,而是一个咆哮,这意味着现在 MockMVC 也会让我失去 StackOverflow 的声誉! :) 绿巨人粉碎!

[编辑] -- 好吧,不管它看起来确实有办法解决这个问题。 [稍后编辑] 不幸的是,我发现的解决方法不再可用。

关于java - Spring-Test-MVC/MockServletContext - 内容在测试中为空但在 Tomcat 上工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11046710/

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