夸克如何处理注射问题?



我正在为我的应用程序做quarkus单元测试。我可能错过了一些东西,但我有一个连接到数据库的问题。对于单元测试,我不需要数据库连接,但是当我注入服务时,Quarkus会自动尝试连接到数据库。如何模拟服务内部的存储库?

错误如下:io.netty.channel.AbstractChannel$AnnotatedConnectException: Connection refused: no further information: localhost/127.0.0.1:3306

下面是我的测试类:
@QuarkusTest
class MyTestClass {
@InjectMock
MerchantRepository merchantRepository;
@Inject
MerchantService merchantService; // Problem with this injection I think
@Inject
MerchantMapper merchantMapper; 
@Test
void testupdate()  {
MerchantDTO merchantDTO = new MerchantDTO();
merchantDTO.setId("id");
merchantDTO.setSomething2("hello");
merchantDTO.setSomething3("hello");
merchantDTO.setSomething4("hello");
merchantDTO.setSomething5(false);

String id = "id";
MerchantBO merchant = merchantMapper.toBOFromDTO(merchantDTO);
MerchantBO fake = null;
when(merchantRepository.somemethod(merchantDTO.getId())).thenReturn(Uni.createFrom().item(merchant));
when(merchantRepository.somemethod2(Mockito.any(), Mockito.any())).thenReturn(Uni.createFrom().item(fake));
when(merchantRepository.somemethod3(Mockito.any(), Mockito.any(), Mockito.any())).thenReturn(Uni.createFrom().item(fake));
assertEquals(merchantDTO, merchantService.update(id, merchantDTO).await().indefinitely());
}
}

这是我的服务:

@ApplicationScoped
public class MerchantService {
@Inject
MerchantRepository merchantRepository;
@Inject
MerchantMapper merchantMapper;
...
}

你有什么好主意吗?

我试图模拟服务对象内部的存储库,但这也不起作用。

Quarkus Dev Services值得一读。对于大多数数据库,如果在开发/测试时没有配置任何东西,Quarkus将使用testcontainers自动建立一个数据库实例。

这通常比mock更令人满意,因为它节省了大量编写mock的工作,并且行为将更接近现实。看起来你正在使用MariaDB或MySQL,对吗?有一个Quarkus Dev Service for MariaDB,所以我建议检查你的Quarkusapplication.properties,并确保你只有一个URL/连接属性设置为%prod

最新更新