确保模拟调用时条件 return 为假

Make sure a condition return false when mock calling

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

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

}

我想测试 EllaService::invokeEllaAsync 方法。当检查条件 if( !isTrafficIgnored( irisBo ) ) 时,我如何模拟它会 return 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 的信息: here

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

为 EllaConfiguration 引入模拟,并在调用 config.isExternalCostumerFilter(any) 时使其 return 为真。 还要确保 irisBo.getBuyer().isExternalKnownCustomer() return 为真。

这将导致

config.isExternalCostumerFilter( this.env ) && irisBo.getBuyer().isExternalKnownCustomer()

return是真的。 这将使 if( !isTrafficIgnored( irisBo ) ) return 为假。