Home > OS >  Quarkus unit testing - How to deal with injection problems?
Quarkus unit testing - How to deal with injection problems?

Time:11-16

I'm trying to make unit test in quarkus for my application. I'm maybe missing something but I have a connection to database problem. For unit test, I do not need database connection but when I'm injecting my service, automatically, Quarkus try to connect to the database. How do I mock the repository inside of the service ?

Here is the error : io.netty.channel.AbstractChannel$AnnotatedConnectException: Connection refused: no further information: localhost/127.0.0.1:3306

Here is my test class:

@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());
    }

}

Here is my service:

@ApplicationScoped
public class MerchantService {

    @Inject
    MerchantRepository merchantRepository;

    @Inject
    MerchantMapper merchantMapper;

    ...
}

Do you have any idea that could help ?

I tried to to Mock the repository inside of the object of the service and that was also not working.

CodePudding user response:

It's worth reading up on Quarkus Dev Services. For most databases, if nothing is provisioned at dev/test time, Quarkus will automatically stand up an instance of the database using testcontainers.

This is usually much more satisfactory than a mock, because it saves a bunch of work writing mocks, and the behaviour will be closer to reality. It looks like you're using MariaDB or MySQL, is that right? There is a Quarkus Dev Service for MariaDB, so I'd suggest checking your Quarkus application.properties and making sure you only have a URL/connection properties set for %prod.

  • Related