1 回答

TA貢獻1883條經(jīng)驗 獲得超3個贊
似乎沒有辦法抑制 Spring 框架觸發(fā)的事件或推遲應(yīng)用程序上下文的創(chuàng)建。所以我想出了以下解決方法:
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();
}
// ...
}
測試手動觸發(fā)事件處理程序。
@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
// ...
}
}
添加回答
舉報