0

I have camel route as below

public class MainRouteBuilder extends RouteBuilder {

    @Autowired
    private CcsRouteCommonProperties commonProps;

    /**
     * {@inheritDoc}
     */
    @Override
    public void configure() throws Exception {

    }
}

I have written test using ExchangeTestSupport as below

public class MainRouteBuilderTest extends ExchangeTestSupport {

    /**
     * {@inheritDoc}
     */
    @Override
    public RoutesBuilder createRouteBuilder() throws Exception {

    }

    @Test
    public void shouldProcess() throws Exception {

    }
}

I am trying to mock CcsRouteCommonProperties something like below @Mock private CcsRouteCommonProperties commonProps;

How to mock the above field using mockito(@RunWith(MockitoJUnitRunner.class))

ShellDragon
  • 1,712
  • 2
  • 12
  • 24
rocky
  • 753
  • 2
  • 10
  • 26

1 Answers1

0

Direct answer to your question would be to Use @InjectMocks on MainRouteBuilder and let Mockito inject an @Mock or @Spy of CcsRouteCommonProperties. I hope this short guide shall explain it for you.

Solution would be something like

@RunWith(MockitoJUnitRunner.class)
    public class MainRouteBuilderTest extends ExchangeTestSupport {

        @Mock
        CcsRouteCommonProperties commonProps;

        @InjectMocks
        MainRouteBuilder routeBuilder;

        @Override
        public RoutesBuilder createRouteBuilder() throws Exception {
                return routeBuilder;
        }

        @Test
        public void shouldProcess() throws Exception {

                when(commonProps.getSomething()).thenReturn(new Something());
        }
    }

However, if I am in your place, I'd avoid @Autowired magic and use clearly stated dependencies using constructor injection.

Route Builder

public class MainRouteBuilder extends RouteBuilder {
private CcsRouteCommonProperties commonProps;
    public MainRouteBuilder( CcsRouteCommonProperties commonProps) {
        this.commonProps =  commonProps;
    }
    /**
        * {@inheritDoc}
        */
    @Override
    public void configure() throws Exception {

    }
}

Test

@RunWith(MockitoJUnitRunner.class)
public class MainRouteBuilderTest extends ExchangeTestSupport {

    @Mock
    CcsRouteCommonProperties commonProps;

    @Override
    public RoutesBuilder createRouteBuilder() throws Exception {
            return new MainRouteBuilder(commonProps);
    }

    @Test
    public void shouldProcess() throws Exception {

    }
}
ShellDragon
  • 1,712
  • 2
  • 12
  • 24