У меня есть класс EllaService
, и я бы хотел проверить там метод EllaService::isTrafficIgnored
. Код указан ниже,
@Service
public class EllaService {
@Autowired
@Qualifier( ELLA_CONNECTOR_BEAN_NAME )
private EntityServiceConnectable<EllaResponseDto> connector;
@Autowired
@Getter
private EllaFilterConfigHolder configHolder;
@Autowired
@Getter
private EllaConfiguration config;
@Autowired
private Environment env;
protected 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() );
}
// ........................
}
Я предоставил 2 теста для метода в классе теста,
@RunWith( PowerMockRunner.class )
@PrepareForTest( EllaDtoConverter.class )
public class EllaServiceTest {
private static final String VALID_TRX_ID = "valid-trx-id";
private static final String VALID_GW_ID = "valid-gw-id";
@InjectMocks
private EllaService ellaService;
private IrisBo validIrisBo;
@Mock
private EllaRequestDto ellaRequestDto;
@Mock
private EntityServiceConnectable<EllaResponseDto> entityServiceConnector;
@Mock
private EllaResponseDto ellaResponseDto;
@Mock
private EllaConfiguration ellaConfiguration;
@Mock
private EllaFilterConfigHolder ellaFilterConfigHolder;
@Mock
private EllaService ellaServiceMock;
@Mock
private Environment environment;
@SuppressWarnings( "unchecked" )
@Before
public void setup() {
PowerMockito.mockStatic( EllaDtoConverter.class );
when( EllaDtoConverter.convertToRequest( any() ) ).thenReturn( ellaRequestDto );
ServiceResponse<EllaResponseDto> validServiceResponseMock = mock( ServiceResponse.class );
when( entityServiceConnector.call( any(), (HttpHeaders) any() ) ).thenReturn( validServiceResponseMock );
when( validServiceResponseMock.isSuccess() ).thenReturn( true );
when( validServiceResponseMock.getResponse() ).thenReturn( ellaResponseDto );
when( validServiceResponseMock.getErrorMessage() ).thenReturn( "" );
when( ellaServiceMock.getConfigHolder() ).thenReturn( ellaFilterConfigHolder );
when( ellaServiceMock.getConfig() ).thenReturn( ellaConfiguration );
when( ellaConfiguration.isExternalCostumerFilter( any() ) ).thenReturn( false );
when( ellaConfiguration.isInternalCostumerFilter( any() ) ).thenReturn( false );
when( ellaConfiguration.extractShopIdsToFilter( any() ) ).thenReturn( "" );
when( ellaFilterConfigHolder.getShopIdsToFilterSet() ).thenReturn( new HashSet<>() );
validIrisBo = new IrisBo();
RequestInformation requestInfo = Mockito.mock( RequestInformation.class );
when( requestInfo.getTransactionId() ).thenReturn( VALID_TRX_ID );
when( requestInfo.getGatewayRequestId() ).thenReturn( VALID_GW_ID );
OrderBo orderBo = new OrderBo();
orderBo.addProduct( INVOICE );
orderBo.setShopId( 123 );
AddressBo addressBo = new AddressBo();
addressBo.setStreetName( "Rutherfordstraße" );
addressBo.setHouseNumber( "2" );
addressBo.setZipCode( "12489" );
ServiceBo serviceBo = new ServiceBo();
serviceBo.setDate( LocalDate.parse( "2018-11-26" ) );
serviceBo.setExistingCustomer( Boolean.TRUE );
TransactionBo transactionBo = new TransactionBo();
transactionBo.setTrxId( "valid-trx-id" );
transactionBo.setCurrencyCode( "EUR" );
transactionBo.setAmount( 12.5 );
BuyerBo buyerBo = new BuyerBo();
buyerBo.setBillingAddress( addressBo );
buyerBo.setDeliveryAddress( addressBo );
validIrisBo.setRequestInfo( requestInfo );
validIrisBo.setOrder( orderBo );
validIrisBo.setBuyer( buyerBo );
validIrisBo.getBuyer().setBillingAddress( addressBo );
validIrisBo.getBuyer().setDeliveryAddress( addressBo );
validIrisBo.setTrackingId( "9241999998422820706039" );
validIrisBo.setEmail( "test@ratepay.com" );
validIrisBo.setIp( "123.120.12.12" );
validIrisBo.setFirstName( "Max" );
validIrisBo.setLastName( "Musterman" );
}
@Test
public void testIsTrafficIgnoredWhenExternalCostumerFilterReturnsTrueAndBuyerIsExternalKnownCustomer() {
when( ellaConfiguration.isExternalCostumerFilter( environment ) ).thenReturn( true );
validIrisBo.getBuyer().setExternalKnownCustomer( true );
assertEquals( true, ellaService.isTrafficIgnored( validIrisBo ) );
}
@Test
public void testIsTrafficIgnoredWhenInternalCostumerFilterReturnsTrueAndBuyerIsInternalKnownCustomer() {
when( ellaConfiguration.isInternalCostumerFilter( environment ) ).thenReturn( true );
validIrisBo.getBuyer().setInternalKnownCustomer( true );
assertEquals( true, ellaService.isTrafficIgnored( validIrisBo ) );
}
}
Теперь я бы хотел проверить
а. если условие
if( config.isExternalCostumerFilter( this.env ) && irisBo.getBuyer().isExternalKnownCustomer() )
ложно
б. состояние
if( config.isInternalCostumerFilter( this.env ) && irisBo.getBuyer().isInternalKnownCustomer() )
является false
с.
checkIfShopIdFilterIsApplied( irisBo )
возвращает true
Тогда isTrafficIgnored
также вернет true
.
Мой метод испытаний приведен ниже,
@Test
public void testIsTrafficIgnoredWhenAllOtherConditionsAreFalseButCheckIfShopIdFilterIsAppliedReturnsTrue() throws Exception {
when( ellaConfiguration.isExternalCostumerFilter( environment ) ).thenReturn( false );
when( ellaConfiguration.isInternalCostumerFilter( environment ) ).thenReturn( false );
PowerMockito.when( ellaServiceMock, "checkIfShopIdFilterIsApplied", validIrisBo ).thenReturn( true );
assertTrue( ellaService.isTrafficIgnored( validIrisBo ) );
}
Я получаю NullPointerException
исключение, указанное ниже,
java.lang.NullPointerException
at com.ratepay.iris.ella.service.EllaService.checkIfShopIdFilterIsApplied(EllaService.java:118)
Я обновил предоставленный метод теста,
@Test
public void testIsTrafficIgnoredWhenAllOtherConditionsAreFalseButCheckIfShopIdFilterIsAppliedReturnsTrue() throws Exception {
EllaFilterConfigHolder e = spy( new EllaFilterConfigHolder() );
doReturn( true ).when( e.getShopIdsToFilterSet().contains( validIrisBo.getOrder().getShopId() ) );
when( ellaConfiguration.isExternalCostumerFilter( environment ) ).thenReturn( false );
when( ellaConfiguration.isInternalCostumerFilter( environment ) ).thenReturn( false );
PowerMockito.when( ellaServiceMock, "checkIfShopIdFilterIsApplied", validIrisBo ).thenReturn( true );
assertTrue( ellaService.isTrafficIgnored( validIrisBo ) );
}
Я получаю стек ошибок,
org.mockito.exceptions.misusing.UnfinishedStubbingException:
Unfinished stubbing detected here:
-> at com.ratepay.iris.ella.service.EllaServiceTest.testIsTrafficIgnoredWhenAllOtherConditionsAreFalseButCheckIfShopIdFilterIsAppliedReturnsTrue(EllaServiceTest.java:216)
E.g. thenReturn() may be missing.
Examples of correct stubbing:
when(mock.isOk()).thenReturn(true);
when(mock.isOk()).thenThrow(exception);
doThrow(exception).when(mock).someVoidMethod();
Hints:
1. missing thenReturn()
2. you are trying to stub a final method, which is not supported
3: you are stubbing the behaviour of another mock inside before 'thenReturn' instruction if completed
at com.ratepay.iris.ella.service.EllaServiceTest.testIsTrafficIgnoredWhenAllOtherConditionsAreFalseButCheckIfShopIdFilterIsAppliedReturnsTrue(EllaServiceTest.java:216)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.internal.runners.TestMethod.invoke(TestMethod.java:68)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:326)
at org.junit.internal.runners.MethodRoadie$2.run(MethodRoadie.java:89)
at org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:97)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.executeTest(PowerMockJUnit44RunnerDelegateImpl.java:310)
Как мне исправить мой тест?
Обновление
У меня такое чувство, что мой вопрос неясен. Я хотел бы знать, как я высмеиваю утверждение checkIfShopIdFilterIsApplied( irisBo )
, чтобы вернуть true
?