Java 确保模拟调用时条件返回false

Java 确保模拟调用时条件返回false,java,junit,mockito,powermock,Java,Junit,Mockito,Powermock,我有一个类,下面提供了代码 @Service public class EllaService { private static final String SHOP_ID_STRING_SEPARATOR = ","; public static final int IRIS_ACCEPT = 0; public static final int IRIS_REJECT = 100; @Autowired @Qualifier( ELLA_CONNE

我有一个类,下面提供了代码

@Service
public class EllaService {

    private static final String SHOP_ID_STRING_SEPARATOR = ",";

    public static final int IRIS_ACCEPT = 0;
    public static final int IRIS_REJECT = 100;

    @Autowired
    @Qualifier( ELLA_CONNECTOR_BEAN_NAME )
    private EntityServiceConnectable<EllaResponseDto> connector;

    @Autowired
    @Getter
    private EllaFilterConfigHolder configHolder;

    @Autowired
    @Getter
    private EllaConfiguration config;

    @Autowired
    private Environment env;

    /**
     * Initialize the component.
     */
    @PostConstruct
    public void initialize() {
        createCustomFilters();
    }

    // ========================================================================

    /**
     * Asynchronously call Ella. Determine if traffic is applicable for Ella and if yes forward to Ella.
     *
     * @param irisBo
     * @return List<ResultBo>
     * @throws EllaGatewayUnsuccessfulResponseException
     */
    @Async
    public void invokeEllaAsync( final IrisBo irisBo ) throws EllaGatewayUnsuccessfulResponseException {

        if( !isTrafficIgnored( irisBo ) ) {

            try {
                callEllaService( irisBo );
            }
            catch( EllaGatewayUnsuccessfulResponseException ex ) {
                throw new EllaGatewayUnsuccessfulResponseException( ex.getMessage(), ex.getCause() );
            }

        }
    }

    // ========================================================================

    private boolean isTrafficIgnored( IrisBo irisBo ) {

        if( config.isExternalCostumerFilter( this.env ) && irisBo.getBuyer().isExternalKnownCustomer() ) {
            return true;
        }

        if( config.isInternalCostumerFilter( this.env ) && irisBo.getBuyer().isInternalKnownCustomer() ) {
            return true;
        }

        return checkIfShopIdFilterIsApplied( irisBo );

    }

    // ========================================================================

    private boolean checkIfShopIdFilterIsApplied( IrisBo irisBo ) {
        return configHolder.getShopIdsToFilterSet().contains( irisBo.getOrder().getShopId() );

    }

    // ========================================================================

    private void callEllaService( final IrisBo irisBo ) throws EllaGatewayUnsuccessfulResponseException {
        HttpHeaders elladHeaders = createRequestHeaders( irisBo );

        ServiceResponse<EllaResponseDto> response = connector.call( EllaDtoConverter.convertToRequest( irisBo ), elladHeaders );

        if( !response.isSuccess() ) {
            throw new EllaGatewayUnsuccessfulResponseException( response.getErrorMessage(), response.getException().getCause() );
        }
    }

    // ========================================================================

    private void createCustomFilters() {
        configHolder.setExternalCustomerFilterEnabled( config.isExternalCostumerFilter( env ) );
        configHolder.setInternalCustomerFilterEnabled( config.isInternalCostumerFilter( env ) );
        configHolder.setShopIdsToFilterSet( new HashSet<>( getShopIdsToFilterAsList( config ) ) );
    }

    // ========================================================================

    private List<Integer> getShopIdsToFilterAsList( EllaConfiguration config ) {
        String shopIdListStr = config.extractShopIdsToFilter( this.env );

        return Arrays.asList( shopIdListStr.split( SHOP_ID_STRING_SEPARATOR ) ).stream().map( s -> Integer.parseInt( s ) )
                .collect( Collectors.toList() );
    }

    // ========================================================================

    private HttpHeaders createRequestHeaders( final IrisBo irisBo ) {

        HttpHeaders ellaHeaders = new HttpHeaders();

        ellaHeaders.add( ACCEPT, APPLICATION_JSON_UTF8_VALUE );
        RatepayHeaders.append( ellaHeaders, irisBo.getRequestInfo() );

        return ellaHeaders;
    }

}
@服务
公共服务{
私有静态最终字符串车间_ID_字符串_分隔符=“,”;
公共静态最终整数=0;
公共静态最终int IRIS_REJECT=100;
@自动连线
@限定符(ELLA\u连接器\u BEAN\u名称)
私有实体服务可连接连接器;
@自动连线
@吸气剂
私有过滤器配置器配置持有者;
@自动连线
@吸气剂
私有配置配置;
@自动连线
私人环境署;
/**
*初始化组件。
*/
@施工后
公共无效初始化(){
createCustomFilters();
}
// ========================================================================
/**
*异步调用Ella。确定流量是否适用于Ella,如果是,则转发给Ella。
*
*@param irisBo
*@返回列表
*@GatewayUnsuccessfulResponseException
*/
@异步的
public void invokeEllaAsync(最终IrisBo IrisBo)抛出网关未成功响应异常{
如果(!isTrafficIgnored(irisBo)){
试一试{
呼叫服务(irisBo);
}
捕获(网关未成功响应异常异常){
抛出新的EllaGatewayUnsuccessfulResponseException(例如getMessage(),例如getCause());
}
}
}
// ========================================================================
专用布尔值isTrafficIgnored(IrisBo-IrisBo){
if(config.isExternalCostumerFilter(this.env)和&irisBo.getBuyer().isExternalKnownCustomer()){
返回true;
}
if(config.isInternalCustomerFilter(this.env)和&irisBo.getBuyer().isInternalKnownCustomer()){
返回true;
}
退货支票(irisBo);
}
// ========================================================================
专用布尔值checkIfShopIdFilterIsApplied(IrisBo IrisBo){
返回configHolder.getShopIdsToFilterSet().contains(irisBo.getOrder().getShopId());
}
// ========================================================================
私有无效调用服务(最终IrisBo IrisBo)抛出网关未成功响应异常{
HttpHeaders-elladHeaders=createRequestHeaders(irisBo);
ServiceResponse response=connector.call(EllaDtoConverter.ConvertRequest(irisBo),elladHeaders);
如果(!response.issucess()){
抛出新的EllaGatewayUnsuccessfulResponseException(response.getErrorMessage(),response.getException().getCause());
}
}
// ========================================================================
私有void createCustomFilters(){
configHolder.setExternalCustomerFilterEnabled(config.isExternalCostumerFilter(env));
setInternalCustomerFilterEnabled(config.isInternalCustomerFilter(env));
setShopIdsToFilterSet(新哈希集(getShopIDstoFilterList(config));
}
// ========================================================================
私有列表GetShopIDstoFilteraList(配置){
字符串shopIdListStr=config.extractShopIdsToFilter(this.env);
返回Arrays.asList(shopIdListStr.split(SHOP\u ID\u STRING\u SEPARATOR)).stream().map(s->Integer.parseInt)
.collect(Collectors.toList());
}
// ========================================================================
私有HttpHeaders createRequestHeaders(最终IrisBo IrisBo){
HttpHeaders=新的HttpHeaders();
添加(接受、应用程序\u JSON\u UTF8\u值);
append(ellaHeaders,irisBo.getRequestInfo());
返回标题;
}
}

我想测试
EllaService::invokeEllaAsync
方法。如果选中(!isTrafficIgnored(irisBo))条件时,它将返回
false

有一些框架可以帮助您准确地执行此操作。 使用Mockito 例如:

MyList listMock = Mockito.mock(MyList.class);
doAnswer(invocation -> "Always the same").when(listMock).get(anyInt());

String element = listMock.get(1);
assertThat(element, is(equalTo("Always the same")));
您可以在官方文档中进一步了解Mockito:
有一些框架可以帮助您做到这一点。 使用Mockito 例如:

MyList listMock = Mockito.mock(MyList.class);
doAnswer(invocation -> "Always the same").when(listMock).get(anyInt());

String element = listMock.get(1);
assertThat(element, is(equalTo("Always the same")));
您可以在官方文档中进一步了解Mockito:
我看到了不同的方法,其中一种是:

为配置引入模拟,并在调用
config.isExternalCostumerFilter(any)
时使其返回true。 还要确保
irisBo.getBuyer().isExternalKnownCustomer()
返回true

这将导致

config.isExternalCostumerFilter( this.env ) && irisBo.getBuyer().isExternalKnownCustomer()
返回真值。
如果(!isTrafficIgnored(irisBo))返回false,则会使

我看到了不同的方法,其中一种方法是:

为配置引入模拟,并在调用
config.isExternalCostumerFilter(any)
时使其返回true。 还要确保
irisBo.getBuyer().isExternalKnownCustomer()
返回true

这将导致

config.isExternalCostumerFilter( this.env ) && irisBo.getBuyer().isExternalKnownCustomer()
返回真值。
如果(!isTrafficIgnored(irisBo))
返回false,则会使
变为false。

到目前为止您尝试过什么吗?这需要是UT和IT吗?一般来说,建议使用构造函数或至少setter注入而不是参数注入。现在的Spring不再使用参数注入。这显著简化了测试,因为您不需要Spring或任何其他基于反射的实用程序类(如Whitebox、ReflectionUtils等)将值注入您的被测组件或系统(SUT),但可以在构建测试主题期间简单地提供这些值。到目前为止,您尝试过什么吗?这需要是UT和IT吗?一般来说,建议使用构造函数或至少setter注入而不是参数注入。春天没有