1 回答
TA贡献1883条经验 获得超3个赞
似乎没有办法抑制 Spring 框架触发的事件或推迟应用程序上下文的创建。所以我想出了以下解决方法:
import org.springframework.core.env.Environment;
public class Example {
private boolean skipNextEvent;
@Autowired
public Example(Environment environment) {
skipNextEvent = environment.acceptsProfiles("test");
}
@EventListener
public void onApplicationEvent(ContextRefreshedEvent event) {
if (skipNextEvent) {
skipNextEvent = false;
return;
}
startWebSocketConnection();
}
// ...
}
测试手动触发事件处理程序。
@ExtendWith(SpringExtension.class)
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
@SpringBootTest
@ActiveProfiles("test") // set profile "test"
public class WebSocketDataSourceTest {
@Autowired
private Example example;
@Autowired
private WebSocketServer server;
@Test
public void shouldWork() {
// ...
example.onApplicationEvent(null); // trigger manually
// ...
}
}
添加回答
举报