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

时间:2019-06-04 12:32:41

标签: 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_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 ) )被选中时它将返回false

2 个答案:

答案 0 :(得分:1)

有些框架可以帮助您做到这一点。 使用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: git's docs

答案 1 :(得分:1)

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

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

这将导致

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

返回true。 这样会使if( !isTrafficIgnored( irisBo ) )返回false。