如何在 ExchangeTestSupport 中使用 mockito



>我有骆驼路线如下

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

我已经使用ExchangeTestSupport进行了如下书面测试

public class MainRouteBuilderTest extends ExchangeTestSupport {
    /**
     * {@inheritDoc}
     */
    @Override
    public RoutesBuilder createRouteBuilder() throws Exception {
    }
    @Test
    public void shouldProcess() throws Exception {
    }
}

我试图模拟CcsRouteCommonProperties,如下所示@Mock私有 CcsRouteCommonProperties commonProps;

如何使用 mockito(@RunWith(MockitoJUnitRunner.class)) 模拟上述字段

对您的问题的直接回答是在MainRouteBuilder上使用@InjectMocks,让 Mockito 注入@Mock@Spy CcsRouteCommonProperties。我希望这个简短的指南能为您解释它。

解决方案将是这样的

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

但是,如果我在你的位置上,我会避免@Autowired魔法,并使用构造函数注入使用明确声明的依赖项。

路线生成器

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

测试

@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 {
    }
}

相关内容

  • 没有找到相关文章

最新更新