- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
在我的 Spring Boot 应用程序中,我也使用了 websockets。一切正常,正如在生产中预期的那样。
现在我开始用 Spring-Boot-Test 创建单元测试。
每次我启动 @SpringBootTest 时,我都会收到以下异常(缩短):
java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'createWebSocketContainer' defined in class path resource [com/package/spring/ws/MyWebsocketConfig.class]: Invocation of init method failed;
Caused by: java.lang.IllegalStateException: Attribute 'javax.websocket.server.ServerContainer' not found in ServletContext
java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:125)
at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:108)
at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:190)
at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:132)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:246)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:227)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:246)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
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:190)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'createWebSocketContainer' defined in class path resource [com/package/spring/ws/MyWebsocketConfig.class]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: Attribute 'javax.websocket.server.ServerContainer' not found in ServletContext
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1778)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:593)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:830)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:877)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:775)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:316)
at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:127)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:99)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:117)
... 24 more
Caused by: java.lang.IllegalStateException: Attribute 'javax.websocket.server.ServerContainer' not found in ServletContext
at org.springframework.util.Assert.state(Assert.java:73)
at org.springframework.web.socket.server.standard.ServletServerContainerFactoryBean.afterPropertiesSet(ServletServerContainerFactoryBean.java:117)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1837)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1774)
... 39 more
package com.package.spring.ws;
// removed imports
@Configuration
@EnableWebSocketMessageBroker
public class MyWebsocketConfig extends AbstractSessionWebSocketMessageBrokerConfigurer<Session> {
private final Logger logger = LogManager.getLogger(MyWebsocketConfig.class);
private int MAX_MESSAGE_SIZE = 1024 * 1024 * 16;
@Override
protected void configureStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/wss")
.setAllowedOrigins("*")
.withSockJS();
}
@Override
public void configureWebSocketTransport(WebSocketTransportRegistration registration) {
registration.setMessageSizeLimit(MAX_MESSAGE_SIZE);
registration.setSendBufferSizeLimit(MAX_MESSAGE_SIZE);
registration.setSendTimeLimit(20000);
super.configureWebSocketTransport(registration);
}
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.setApplicationDestinationPrefixes("/app");
config.enableSimpleBroker("/queue", "/events", "/topic");
config.setCacheLimit(1024 * 10);
super.configureMessageBroker(config);
}
// This is breaking my Spring Unit Tests.
@Bean
public ServletServerContainerFactoryBean createWebSocketContainer() {
ServletServerContainerFactoryBean container = new
ServletServerContainerFactoryBean();
container.setMaxTextMessageBufferSize(MAX_MESSAGE_SIZE);
container.setMaxBinaryMessageBufferSize(MAX_MESSAGE_SIZE);
return container;
}
}
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.package</groupId>
<artifactId>MyProject</artifactId>
<version>0.8.4-RELEASE</version>
<packaging>war</packaging>
<name>My Project</name>
<description>MyProject Server</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- Problem exists, with and without this websocket dependency -->
<dependency>
<groupId>javax.websocket</groupId>
<artifactId>javax.websocket-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-messaging</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
package com.packge.spring;
// removed imports
@ComponentScan({"com.package.spring", "com.packe.spring.security", "com.package.endpoints"})
@EnableJpaRepositories(basePackages = "com.package.db")
@EntityScan(value = "com.package.db")
@SpringBootApplication
public class MyApplication extends SpringBootServletInitializer {
@Value("my.session.cookie-name")
private String cookieName = ApplicationConfig.SESSION_COOKIE_NAME;
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
@RunWith(SpringRunner.class)
@SpringBootTest(classes = MyApplication.class, webEnvironment = SpringBootTest.WebEnvironment.MOCK)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class LedgerTreeMovementsTest {
@Test
public void test0_testXYZ() {
}
}
最佳答案
感谢 GSSwain,他引导我走向正确的方向,我现在能够解决我的问题。
它似乎只有在 @SpringBootTest
时才会出现属性 webEnviroment
设置为 MOCK
, 或 NONE
.使用定义的或随机的端口告诉 Spring 加载正确的 ServletContext。
如果您不想为简单的测试加载完整的上下文,有多种方法可以解决这个问题。
方案一
这是大多数人需要的。添加额外的 @WebAppConfiguration
对测试类的注释,它告诉 Spring 加载一个适当的 ServletContext,其中包含 ServerContainer 的模拟属性条目。
解决方案2
对于我的需要,在许多测试用例中,这仍然是过多的背景膨胀,我不需要的东西。所以我在 Bean 创建本身中添加了一个检查,并添加了一个属性来通过 application.properties 打开或关闭检查。
在您的 WebsocketConfig 类中:
@Autowired
private ServletContext servletContext;
private boolean ignoreNullWsContainer;
@Bean
public ServletServerContainerFactoryBean createWebSocketContainer() {
// Check if null-container is allowed to prevent Exceptions
if (ignoreNullWsContainer) {
// Check if attribute is set in the ServletContext
ServerContainer serverContainer = (ServerContainer) this.servletContext.getAttribute("javax.websocket.server.ServerContainer");
if (serverContainer == null) {
logger.error("Could not initialize Websocket Container in Testcase.");
return null;
}
}
ServletServerContainerFactoryBean container = new ServletServerContainerFactoryBean();
container.setMaxTextMessageBufferSize(MAX_MESSAGE_SIZE);
container.setMaxBinaryMessageBufferSize(MAX_MESSAGE_SIZE);
return container;
}
@Value("${project.ignore-null-websocket-container:false}")
private void setIgnoreNullWsContainer(String flag) {
this.ignoreNullWsContainer = Boolean.parseBoolean(flag);
}
并在您的 test src 资源目录中的 application.properties 中(默认目录 src/test/resources/application.properties
project.ignoreNullWsContainer = true
这样,如果你没有在你的生产环境属性文件中设置这个属性,如果 ServerContainer 有问题,Spring 仍然会失败。
关于spring-boot - 在 ServletContext 中找不到属性 ServerContainer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56065309/
在我的 Spring Boot 应用程序中,我也使用了 websockets。一切正常,正如在生产中预期的那样。 现在我开始用 Spring-Boot-Test 创建单元测试。 每次我启动 @Spri
在我的 JIRA 插件中,我创建了一个 WebListener,它将一个 websocket 端点添加到 SeverContainer。 问题是,当我更改我的插件并将其上传到 JIRA 时,新代码没有
尝试使用 SockJS 连接到 Spring Websocket 时出现错误 org.springframework.web.util.NestedServletException: Request
我正在尝试将带有 Web 套接字的 Spring Boot (2.0.5) Web 应用程序 (war) 部署到 Tomcat 8.5.37 服务器,它以前使用 Tomcat 7。我的 Web 套接字
我正在使用 Glassfish 4.1 部署我的 WAR 应用程序。无法连接到 websocket,从 glassfish 获取此消息: 我的网络套接字配置 @Configuration @Enabl
我在尝试在 CometD 上启用 WebSocket 时遇到问题。我的配置如下: - CometD 3.0.5 - jetty 9.0.6, - SpringMVC 3.2.4 web.xml
2018-08-15 16:05:57.353:WARN:oejw.WebAppContext:main: Failed startup of context o.e.j.w.WebAppContex
我是一名优秀的程序员,十分优秀!