我将使用Micronaut文档中的代码(声明式Http客户机)--我使用的是Spock
PetOperations.java
@Validated
public interface PetOperations {
@Post
Single<Pet> save(@NotBlank String name, @Min(1L) int age);
}我有一个声明式客户端:
@Client("/pets")
public interface PetClient extends PetOperations {
@Override
Single<Pet> save(String name, int age);
}当我运行一个测试类时,我想调用(@)另一个类( PetDummy )而不是PetClient,PetDummy类位于我的测试文件夹中。
@Primary
@Replaces(PetClient.class)
@Singleton
public class PetDummy implements PetOperations {
@Override
public Single<Pet> save(String name, int age) {
Pet pet = new Pet();
pet.setName(name);
pet.setAge(age);
// save to database or something
return Single.just(pet);
}
}考试班:
class PetTest extends Specification {
@Shared
@AutoCleanup
ApplicationContext applicationContext = ApplicationContext.run();
//EmbeddedServer server = applicationContext.getBean(EmbeddedServer.class).start();
PetClient client = applicationContext.getBean(PetOperations.class);
def 'test' (){
given: 'name and age'
when:
client.save("Hoppie", 1);
then:
noExceptionThrown()
}
}但是,最后的称为,我也尝试过使用@Factory注释,但没有成功
PetClient扩展了PetOperations和PetDummy实现了PetOperations,如果它们都实现了,那么使用@代替.
还有什么我可以试试的吗?
谢谢!
另一期:
现在它已经工作了,PetClient是我的PetService中的一个依赖项。当我测试我的PetService时,它仍然调用PetClient而不是PetDummy。
我想这与applicationContext有关,你会看到
PetService:
PetService {
@Inject
PetClient client;
buyFood(){
//...
Single<Pet> pet = client.save("Hoppie", 1));
}
}PerService测试:
class PetServiceTest extends ApplicationContextSpecification {
@Subject
@Shared
PetService petService = applicationContext.getBean(PetService)
PetOperations client = applicationContext.getBean(PetOperations.class) //client is not used here
def 'test' (){
given:
when:
petService.buyFood()
then:
noExceptionThrown()
}
}我认为我需要从applicationContext中“进入”PetService,告诉“使用PetDummy”实现(在测试类中),因为ApplicationContextSpecification属于另一个模块。
ApplicationContextSpecification是:
abstract class ApplicationContextSpecification extends Specification implements ConfigurationFixture {
@AutoCleanup
@Shared
ApplicationContext applicationContext = ApplicationContext.run(configuration)
/* def cleanup() {
assert !hasLeakage()
}*/
}ConfigurationFixture包含数据库的属性(Hibernate)
发布于 2021-08-11 12:17:53
您已经在检索PetClient bean实现:
PetClient client = applicationContext.getBean(PetOperations.class);如果用适当的类型调用,那么应该提供替换虚拟bean实现:
PetOperations client = applicationContext.getBean(PetOperations.class);https://stackoverflow.com/questions/68740533
复制相似问题