M
M
MaxLich2019-01-09 13:12:22
Java
MaxLich, 2019-01-09 13:12:22

How to replace an object with a stub in the spring context for tests?

Hello. I use Activity in my application, and decided to write unit tests to test the start of a process, end the current user taskone, get lists of the current ones user task, etc. In the scheme, I use spring beans:

<serviceTask id="get_timer_value_1" name="get_timer_value_1" activiti:expression="${activitiGetTimerValueDelegateService.getTimerValue(9,1,execution)}"></serviceTask>

In this case activitiGetTimerValueDelegateService, it's a bean.
I need that call
activitiGetTimerValueDelegateService.getTimerValue(9,1,execution)
always returned one constant value (in the application, it takes the value for the timer from the database).
I created a separate spring context for tests for, but stumbled on adding a mock of this bean to this context. What is the easiest way to do this?
Threat I would not want to change the name of the bean or bpm-scheme for this

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Osipov, 2019-01-10
@Shiftuia

You can try to write a separate class in which your object will be created.
The general idea is to use Primary, which will be given preference when creating a bean
Something like

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import static org.mockito.Mockito.*;

@Configuration
public class MockConfiguration {


  @Primary
  @Bean
  public ActivitiGetTimerValueDelegateService activitiGetTimerValueDelegateService() {
    ActivitiGetTimerValueDelegateService service = mock(ActivitiGetTimerValueDelegateService.class);
    when(service.getTimerValue(any(), any(), any())).thenReturn(42);

    return service;
  }

}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question