Spring websocket测试:存储库在应用回滚事务时看不到实体

时间:2017-04-02 12:39:11

标签: java spring spring-boot spring-test spring-websocket

我遇到了一个测试websocket端点的情况,当我使用rollbacked事务来回滚测试期间所做的所有更改时,我有一个不可预测的行为。

我创建了一个简单的例子来向我们展示发生了什么。

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特定

@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();
        }
    }
}

最终是UserHandlerTest.java。我使用okHttp3作为websocket测试客户端:

@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);
        }
    }

}

我的测试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

上面的所有代码都没问题,测试通过了。但是假设我不想弄乱数据库,所以我在所有测试方法上使用@Transactional来在测试完成后回滚所有更改。

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
@Transactional
public class UserHandlerTest {
  // the same as above
}

然后UserRepository没有找到保存在setUp测试方法中的用户。

java.lang.AssertionError: 
Expected: is "ok"
but: was "user not found"

我试图在其余端点上重现相同的情况,它在那里工作。我们来看看。

UserController.java

@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping(path = "/api/user")
    public @ResponseBody User getUser(String name){
        return userService.getUser(name);
    }

}

和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")));
    }

}

传递上一次测试并回滚事务。

我希望在测试websocket端点时看到相同的行为。

有人能指出我的差异在哪里吗?为什么春天会这样做?

1 个答案:

答案 0 :(得分:3)

这基本上是Spring Boot @WebIntegrationTest and TestRestTemplate - Is it possible to rollback test transactions?的副本。

  

我希望在测试websocket端点时看到相同的行为。

你做不到。当您声明@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)时,Spring Boot会启动一个嵌入式Servlet容器。

这就是为什么如果你用@Transactional另外注释你的测试,有两个不同的交易:

  1. 测试管理
  2. 弹簧管理
  3. 对于您的用例,您需要在测试中停止使用@Transactional,并在测试完成后开始手动重置数据库的状态。为此,我建议在@Sql执行阶段使用AFTER_TEST_METHOD。有关示例,请参阅How to execute @Sql before a @Before method

    此致

    Sam( Spring TestContext Framework的作者