当 运行 在 Spring 中处于测试模式时,如何禁用方法?

How can i disable a method when running in test mode in Spring?

我有一个方法如下:

@PostMapping(path = ["/signup"],
        consumes = [(MediaType.APPLICATION_JSON_UTF8_VALUE)])
fun signUp(@RequestBody dto: RegistrationDto)
        : ResponseEntity<Void> {

    val userId : String = dto.userInfo!!.username!!
    val password : String = dto.password!!

    val registered = if(!dto.secretPassword.isNullOrBlank() && dto.secretPassword.equals(adminCode)) {
        authService.createUser(userId, password, setOf("ADMIN"))
    } else {
        authService.createUser(userId, password, setOf("USER"))
    }

    if (!registered) {
        return ResponseEntity.status(400).build()
    }

    val userDetails = userDetailsService.loadUserByUsername(userId)
    val token = UsernamePasswordAuthenticationToken(userDetails, password, userDetails.authorities)

    authenticationManager.authenticate(token)

    if (token.isAuthenticated) {
        SecurityContextHolder.getContext().authentication = token
    }

    /**
     * AMQP
     */
    amqpService.send(dto.userInfo!!, "USER-REGISTRATION")

    return ResponseEntity.status(204).build()
}

如果您注意到我有一个方法 amqpService.send(dto.userInfo!!, "USER-REGISTRATION,当我 运行 处于 "development" 模式时如何禁用此方法?

我想在 运行 处于测试模式时禁用 RabbiqMQ,这样这个方法就不会被调用?

谢谢

在测试模式下,您可以替换 mock 上的 amqpService:

@Configuration
public class AmqpConfig {

   @Profile("test")
   @Bean 
   public AmqpService amqpService(){
     return mock(AmqpService.class);
   }   
}

或者您可以在测试中立即使用 @MockBean class 来替换测试中模拟中的这个 bean。

所以你运行一个模拟的方法而不是一个真实的对象。