Mocking in component tests

83 Views Asked by At

I am relatively new to component tests and testcontainer, kindly bear with me.

I have the following call structure in my code.

Rest endpoint -> publish jms - > onMessage - > calling a service

I want to Mock the service implementation and when I will trigger the REST endpoint, I want the onMessage to use the Mocked service. How can I instruct the jms to use the mocked service and not the actual one? When I am triggering the REST endpoint, it is using the actual service. I do understand that this is probably the aim/goal of component tests, I was wondering if there is any way to use the mocked service here ?

1

There are 1 best solutions below

1
On

I'm not sure how is testcontainers project related here. Testcontainers basically allows loading the thirdparty (for example, rdbms, mongo, redis, etc) during the test from the docker image and it is available to be used in the test.

In your case, first of all ask yourself what do you want to test exactly. Obviously when it comes to the JMS, if you're using the test container, then you should start the JMS server implementation in the test itself and configure it. However in this case, your code will work with a "real" JMS (from that container) and not with a mock that you're asking about.

Another possible direction is to not start JMS at all (in this case you don't need to use test container) and instead configure your application with a mock behaviour.

For example something like this:

When sending the message over the jms --> then invoke the code of the listener as if its a regular class.

Technical details will really vary depending on the technology stack you're using, but in general you should be able to achieve that by using only Mockito and maybe some kind of code refactoring: you'll have to inject this mock implementation of JMS "behavior" into the rest controller...