I've faced with a situation when I was testing websocket endpoint and when I used rollbacked transaction to rollback all changes made during the test I've got an unpredictable behaviour.
I created an simple example to show us what is happenning.
User.java
@Entity(name = "USERS")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String name;
// getters,setters ommitted
}
UserRepository.java
@Repository
public interface UserRepository extends JpaRepository<User,Long> {
User getUserByName(String name);
}
UserService.java
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public User getUser(String name){
return userRepository.getUserByName(name);
}
}
Websocket specific
@Configuration
@EnableWebSocket
public class Config implements WebSocketConfigurer {
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry webSocketHandlerRegistry) {
webSocketHandlerRegistry.addHandler(userHandler(), "/api/user");
}
@Bean
UserHandler userHandler(){
return new UserHandler();
}
}
UserHandler.java
public class UserHandler extends TextWebSocketHandler{
@Autowired
private UserService userService;
@Override
public void afterConnectionEstablished(WebSocketSession session) {
try {
HttpHeaders headers = session.getHandshakeHeaders();
List<String> userNameHeader = headers.get("user_name");
if (userNameHeader == null || userNameHeader.isEmpty()){
session.sendMessage(new TextMessage("user header not found"));
return;
}
String userName = userNameHeader.get(0);
User user = userService.getUser(userName);
if (user == null){
session.sendMessage(new TextMessage("user not found"));
return;
}
session.sendMessage(new TextMessage("ok"));
} catch (Throwable e) {
e.printStackTrace();
}
}
}
And eventually UserHandlerTest.java. I use okHttp3 as a websocket test client:
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class UserHandlerTest {
@Autowired
private UserRepository userRepository;
private User testUser;
private BlockingQueue<String> messages = new LinkedBlockingQueue<>();
private OkHttpClient okHttpClient;
@Before
public void setUp(){
okHttpClient = new OkHttpClient();
testUser = new User();
testUser.setName("test");
userRepository.save(testUser);
}
@Test
public void testThatUserExist(){
Request request = new Request.Builder()
.url("ws://127.0.0.1:8080/api/user")
.header("user_name","test")
.build();
WebSocket ws = okHttpClient.newWebSocket(request,new MsgListener());
String msg = null;
try {
msg = messages.poll(5, TimeUnit.SECONDS);
} catch (InterruptedException e) {
System.out.println(e);
}
Assert.assertNotNull(msg);
Assert.assertThat(msg,is("ok"));
}
private class MsgListener extends WebSocketListener{
@Override
public void onOpen(WebSocket webSocket, Response response) {
System.out.println("onOpen:"+response.message());
}
@Override
public void onMessage(WebSocket webSocket, String text) {
System.out.println("onMessage:"+text);
messages.add(text);
}
}
}
And my test aplication.properties:
spring.jpa.database=postgresql
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=update
spring.datasource.username=postgres
spring.datasource.password=******
spring.datasource.driver-class-name=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql://127.0.0.1:5432/USERS_TEST
All the code above is ok and test is passed. But suppose I don't want to mess the db so I use @Transactional
on all test methods to rollback all changes after the test is done.
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
@Transactional
public class UserHandlerTest {
// the same as above
}
And then UserRepository does not find the user saved in setUp test method.
java.lang.AssertionError:
Expected: is "ok"
but: was "user not found"
I tried to reproduce the same situation on the rest endpoint and it works there. Let's see.
UserController.java
@RestController
public class UserController {
@Autowired
private UserService userService;
@GetMapping(path = "/api/user")
public @ResponseBody User getUser(String name){
return userService.getUser(name);
}
}
And UserControllerTest.java:
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
@Transactional
public class UserControllerTest {
@Autowired
private WebApplicationContext webApplicationContext;
private MockMvc mockMvc;
@Autowired
private UserRepository userRepository;
private User testUser;
@Before
public void setUp(){
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
testUser = new User();
testUser.setName("test");
userRepository.save(testUser);
}
@Test
public void testThatUserExist() throws Exception {
mockMvc.perform(get("/api/user")
.param("name","test")
).andExpect(status().isOk())
.andExpect(jsonPath("name").value(is("test")));
}
}
Last test is passed and the transaction is rolled back.
I want to see the same behaviour when I test websocket endpoint.
Could someone point me out where the differencies here? And Why Spring does it?
This is essentially a duplicate of Spring Boot @WebIntegrationTest and TestRestTemplate - Is it possible to rollback test transactions?.
I want to see the same behaviour when I test websocket endpoint.
You can't. When you declare @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
, Spring Boot starts an embedded Servlet container.
That's why there are two different transactions if you additionally annotate your tests with @Transactional
:
For your use case, you will need to stop using @Transactional
in your test and start manually resetting the state of the database after your test completes. For that I'd recommend the use of @Sql
with the AFTER_TEST_METHOD
execution phase. See How to execute @Sql before a @Before method for an example.
Regards,
Sam (author of the Spring TestContext Framework)