在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,当我在"开发"模式下运行时,我如何禁用这个方法?

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

Thanx

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

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

或者,您可以在测试类中立即使用@MockBean来替换测试中mock上的这个bean。

因此,您运行mock方法,而不是实际对象。

最新更新