Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test needing a mock of RabbitTemplate

I have a implementation class which acts as a rabbitMQ sender class, I am trying to write unit test cases for this, but i am having doubts about mocking rabbitmq template. This is my sender class code:

@Service
public class Car implements CarDelegate {

    @Autowired
    private RabbitTemplate rt;

    @Value("${exchange}")
    private String exchange;

    @Value("${queue}")
    private String queue;

    @Override
    public ResponseEntity<String> createCar(String model, String name) {
        Car car = new Car();
        car.setModel(Model);
        car.setName(Name);
        String jsonString;
        jsonString = new ObjectMapper().writeValueAsString(car);
        try {
            rt.convertAndSend(exchange, queue, jsonString);
        } catch (AmqpException e) {
            //to implement
        }
        return new ResponseEntity<>(HttpStatus.ACCEPTED);
    }
}

My sender class is also my implementation method. The test class for it is as below:

@RunWith(MockitoJUnitRunner.class)
public class CarTest {

    private Car car;
    @Mock
    private RabbitTemplate rt;

    @Test
    public void create_valid() {
        Car car = new Car(rt);
        car.create("sedan", "arison");

        String jsonString = "";
        Mockito.doReturn("")
           .when(rabbitTemplate.convertAndSend(null, null, jsonString))
           .myMethod(Mockito.any(createLeadTest_valid.class));
        Mockito.when(rabbitTemplate.convertAndSend(null, null, jsonString)).thenReturn("");
    }

}

What is the correct way to mock rabbit template

like image 201
Aarika Avatar asked Oct 16 '25 19:10

Aarika


1 Answers

For your specific case, no need to add behavior to your mock.

public class CarServiceTest {

    @Test
    public void create_valid() {
        RabbitTemplate rt = Mockito.mock(RabbitTemplate.class);
        CarService car = new CarService(rt);
        ResponseEntity<String> response = car.create("sedan", "arison");

        assertThat(response).isNotNull();
        assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
    }
}

FYI, it is not good practice to manipulate ResponseEntity outside an HTTP adapter (typically a bean annotated with @Controller).

And RabbitTemplate#convertAndSend is supposed to provide a conversion mechanism, so you do not have to use Jackson directly.

Hoping this will help you !

like image 91
Loïc Le Doyen Avatar answered Oct 19 '25 08:10

Loïc Le Doyen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!