我目前正在开发在系统中注册用户的微服务。我想为控制器创建一些集成测试,但是OAuth2和Feign遇到了一些问题。关键是我的控制器方法(我要测试)有一些服务调用,并且在该服务内部还存在一个伪装客户端接口的调用,该接口指向另一个微服务。但是,在此时刻,当假装被调用时,我正在通过OAuth2拒绝访问。有什么方法可以完全存根/模拟此方法,以便当它尝试从伪接口调用方法时返回一些模拟数据吗?
这是我的控制器方法:
@PostMapping
public UserDto register(@Valid @RequestBody AccountRegisterRequest request) {
return accountService.register(accountRegisterRequestConverter.convertTo(request));
}
这是我的帐户服务方法register
:
public UserDto register(Account account) {
UserDto createdUser = authServiceFeignClient.createUser(account.getUserRegistrationDto());
if (nonNull(createdUser)) {
account.setUserId(Long.parseLong(createdUser.getId()));
Account savedAccount = repository.save(account);
System.out.println("Account saved: " + savedAccount.getNickname());
} else {
System.out.println("Account saving error! User was not created.");
}
return createdUser;
}
还有authServiceFeignClient
:
@FeignClient(name = "auth-service", configuration = FeignConfiguration.class)
public interface AuthServiceFeignApi {
@PostMapping(value = "/uaa/user")
UserDto createUser(@RequestBody UserRegistrationDto user);
}
这是我的测试配置,并且测试本身是用Spock编写的:
class AccountIntegrationSpec extends MicroserviceIntegrationSetup implements AccountFixture {
@Autowired
AccountController accountController
@Autowired
AccountService accountService
@Autowired
AccountValidator accountValidator
def setup() {
stubForCreatingDefaultUser()
}
def 'should create user and receive result'() {
given:
def createAccountRequest = createAccountRegisterRequest()
when:
def result = accountController.register(createAccountRequest)
then:
result.username == "Username"
result.id == "1"
}
}
@CompileStatic
@SpringBootTest(classes = AccountServiceApplication.class, webEnvironment = RANDOM_PORT)
@Import(Stubs)
@ActiveProfiles("test")
abstract class MicroserviceIntegrationSetup extends Specification {
@Autowired
DatabaseCleaner databaseCleaner
@Autowired
@Qualifier("authFeignApi")
AuthServiceFeignApi authServiceFeignApi
@Before
def cleanDatabase() {
databaseCleaner.deleteAll()
}
@TestConfiguration
static class Stubs {
DetachedMockFactory factory = new DetachedMockFactory()
@Bean(name = "authFeignApi")
AuthServiceFeignApi authServiceFeignApi() {
factory.Mock(AuthServiceFeignApi)
}
}
def stubForCreatingUser(UserRegistrationDto userRegistrationDto) {
authServiceFeignApi.createUser(userRegistrationDto) >> new UserDto("1", userRegistrationDto.username)
}
def stubForCreatingDefaultUser() {
authServiceFeignApi.createUser(_ as UserRegistrationDto) >> new UserDto("1", "Username")
}
}
总而言之,我希望该测试通过并完全忽略oauth2,并且authServiceFeignClient
也已正确存根/模拟并返回了stubForCreatingDefaultUser
方法中提供的数据。
感谢您的任何帮助,也许这种方法没有意义,然后也欢迎其他建议。