In CrossSellOffersServiceAdapter class, this statement:
crossSellOffersConnectBDS.getBDSCustomerInfo(channelId, customerId, cinSuffix,
countryCode);
Should return the value as it is mocked. But it is returning null value in CrossSellOffersServiceAdapterTest class.
public class CrossSellOffersServiceAdapter implements CrossSellOffersService {
#Autowired
private CrossSellOffersConnectBDS crossSellOffersConnectBDS;
#Autowired
private CrossSellOffersConnectCMP crossSellOffersConnectCMP;
#Autowired
private BDSCustomerHoldings bdsCustomerHoldings;
private static final Logger LOGGER = LoggerFactory.getLogger(CrossSellOffersServiceAdapter.class);
#Override
public Offers getApplicableOffers(String channelId, String customerId, String cinSuffix, String countryCode,
String interactionPoint, String sessionId, Integer numberOfOffers) throws CrossSellOffersException {
bdsCustomerHoldings = crossSellOffersConnectBDS.getBDSCustomerInfo(channelId, customerId, cinSuffix,
countryCode);
CMPOffer cmpOffer = crossSellOffersConnectCMP.getCMPOffers(bdsCustomerHoldings, interactionPoint, sessionId,
numberOfOffers);
Offers offers = getOffers(cmpOffer);
return offers;
}
}
public class CrossSellOffersServiceAdapterTest {
#InjectMocks
private CrossSellOffersServiceAdapter crossSellOffersService;
#Mock
private CrossSellOffersConnectBDSAdapter crossSellOffersConnectBDS;
#Mock
private CrossSellOffersConnectCMPAdapter crossSellOffersConnectCMP;
#Mock
private RestTemplate restTemplate;
#Mock
OffersRequest offersRq;
#Mock
private BDSRequest bdsRequest ;
#Mock
private BDSCustomerHoldings bdsResponse;
#Test
public void getApplicableOffersTest() throws CrossSellOffersException {
Mockito.when(crossSellOffersConnectBDS.getBDSCustomerInfo("MBSG", "S9718016D", "00", "SG")).thenReturn(sampleBDSResponse());
Mockito.when(crossSellOffersConnectCMP.getCMPOffers(bdsResponse, "NEW_CC_ADDON", "IBOXS007", 1)).thenReturn(CrossSellOffersConnectCMPAdapterTest.sampleCMPOffer());
Offers offers = crossSellOffersService.getApplicableOffers("MBSG", "IBOXS007", "00", "SG","NEW_CC_ADDON", "S9718016D", 1);
assertNotNull(offers, "response is not null");
}
}
Think you are missing the mockito init:
import org.mockito.MockitoAnnotations;
#Before
public void setup() {
MockitoAnnotations.initMocks(this);
}
Related
I have a job that looks like this:
#Named
public class MyCamelRouteBuilder extends RouteBuilder {
private static final String JOB_NAME = "abc";
private static final String JOB_METHOD_NAME = "xyz";
private final MyJob myJob;
#Inject
public MyCamelRouteBuilder(MyJob myJob) {
super();
this.myJob = myJob;
}
#Override
public void configure() {
fromF("direct:%s", JOB_NAME)
.routeId(JOB_NAME)
.bean(myJob, JOB_METHOD_NAME)
.end();
fromF("master:some_name_1/some_name_2:scheduler:%s?delay=%s", JOB_NAME, 1234)
.routeId("JobTimer")
.toF("direct:%s", JOB_NAME)
.end();
}
}
A very simplified version of the job class:
#Named
public class MyJob {
private MyJob() {}
}
public void xyz() {
}
}
This does work and it does gets triggered as expected.
The problem starts here:
Now, I also want to create a REST controller that will be able to trigger the exact same job. Something like this:
#Named
#RestController
#RequestMapping
#Validated
public class MyController {
private static final String JOB_NAME = "abc";
private final ProducerTemplate producerTemplate;
#Inject
public MyController(
ProducerTemplate producerTemplate
) {
this.producerTemplate = producerTemplate;
}
#PostMapping(path = "/my_endpoint")
public String run() throws Exception {
producerTemplate.requestBody("direct:" + JOB_NAME);
return "ok";
}
}
But once it reaches this line, the job is not triggered and the request call keeps hanging.
producerTemplate.requestBody("direct:" + JOB_NAME);
Any ideas?
The fix for my problem:
#Named
#RestController
#RequestMapping
#Validated
public class MyController {
private static final String JOB_NAME = "abc";
#Produce("direct:" + JOB_NAME)
private final ProducerTemplate producerTemplate;
private final CamelContext context;
#Inject
public MyController(
ProducerTemplate producerTemplate, CamelContext context
) {
this.producerTemplate = producerTemplate;
this.context = context;
}
#PostMapping(path = "/my_endpoint")
public String run() throws Exception {
Exchange exchange = new DefaultExchange(context);
producerTemplate.send(exchange);
return "ok";
}
}
Note: I already look at and tried some approaches on SO e.g. How to test Spring's declarative caching support on Spring Data repositories?, but as most of them old, I cannot make them work properly and I need a solution with the latest library versions. So, I would be appreciated if you have a look at the question and help.
#Service
#EnableCaching
#RequiredArgsConstructor
public class DemoServiceImpl implements DemoService {
private static final String CACHE_NAME = "demoCache";
private final LabelRepository labelRepository;
private final LabelTranslatableRepository translatableRepository;
private final LanguageService languageService;
#Override
public LabelDTO findByUuid(UUID uuid) {
final Label label = labelRepository.findByUuid(uuid)
.orElseThrow(() -> new EntityNotFoundException("Not found."));
final List<LabelTranslatable> translatableList = translatableRepository.findAllByEntityUuid(uuid);
return new LabelDTO(Pair.of(label.getUuid(), label.getKey()), translatableList);
}
}
I created the following Unit Test to test caching for the nethod above:
#EnableCaching
#ImportAutoConfiguration(classes = {
CacheAutoConfiguration.class,
RedisAutoConfiguration.class
})
#ExtendWith(MockitoExtension.class)
class TextLabelServiceImpl_deneme_Test {
#Autowired
private CacheManager cacheManager;
#InjectMocks
private LabelService labelService;
#Mock
private LabelRepository labelRepository;
#Mock
private LabelTranslatableRepository translatableRepository;
#Test
void test_Cache() {
UUID uuid = UUID.randomUUID();
final TextLabel textLabel = new TextLabel();
textLabel.setId(1);
textLabel.setKey("key1");
TextLabelTranslatable textLabelTranslatable = new TextLabelTranslatable();
textLabelTranslatable.setEntityUuid(uuid);
textLabelTranslatable.setLanguage(SupportedLanguage.fr);
textLabelTranslatable.setValue("value1");
final List<TextLabelTranslatable> translatableList = new ArrayList<>();
translatableList.add(textLabelTranslatable);
when(labelRepository.findByUuid(uuid)).thenReturn(Optional.of(textLabel));
when(translatableRepository.findAllByEntityUuid(uuid)).thenReturn(translatableList);
TextLabelDTO result1 = labelService.findByUuid(uuid);
TextLabelDTO result2 = labelService.findByUuid(uuid);
assertEquals(result1, result2);
Mockito.verify(translatableRepository, Mockito.times(1)).findAllByEntityUuid(uuid);
}
I am not sure if there is a missing part in my test, but at the last line (Mockito.verify()), it returns 2 instead of 1 that means caching not works. But it is working properly and there is a problem in my test I think. How should I complete the unit test to check the caching properly?
You need to annotate the service class method with #Cacheable. Try to follow the code in this tutorial. The following test code works as expected
#Import({CacheConfig.class, DemoServiceImpl.class})
#ExtendWith(SpringExtension.class)
#EnableCaching
#ImportAutoConfiguration(classes = {
CacheAutoConfiguration.class,
RedisAutoConfiguration.class
})
class DemoServiceImplTest {
#MockBean
private LabelRepository labelRepository;
#Autowired
private DemoServiceImpl demoService;
#Autowired
private CacheManager cacheManager;
#TestConfiguration
static class EmbeddedRedisConfiguration {
private final RedisServer redisServer;
public EmbeddedRedisConfiguration() {
this.redisServer = new RedisServer();
}
#PostConstruct
public void startRedis() {
redisServer.start();
}
#PreDestroy
public void stopRedis() {
this.redisServer.stop();
}
}
#Test
void givenRedisCaching_whenFindItemById_thenItemReturnedFromCache() {
UUID id = UUID.randomUUID();
Label aLabel = new Label(id, "label");
Mockito.when(labelRepository.findById(id)).thenReturn(Optional.of(aLabel));
Label labelCacheMiss = demoService.findByUuid(id);
Label labelCacheHit = demoService.findByUuid(id);
Mockito.verify(labelRepository, Mockito.times(1)).findById(id);
}
}
With this service class code:
#Service
#RequiredArgsConstructor
#EnableCaching
public class DemoServiceImpl {
public static final String CACHE_NAME = "demoCache";
private final LabelRepository labelRepository;
#Cacheable(value = CACHE_NAME)
public Label findByUuid(UUID uuid) {
return labelRepository.findById(uuid)
.orElseThrow(() -> new EntityNotFoundException("Not found."));
}
}
And this CacheConfig:
#Configuration
public class CacheConfig {
#Bean
public RedisCacheManagerBuilderCustomizer redisCacheManagerBuilderCustomizer() {
return (builder) -> builder
.withCacheConfiguration(DemoServiceImpl.CACHE_NAME,
RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofMinutes(10)));
}
#Bean
public RedisCacheConfiguration cacheConfiguration() {
return RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofMinutes(60))
.disableCachingNullValues()
.serializeValuesWith(
RedisSerializationContext.SerializationPair.fromSerializer(
new GenericJackson2JsonRedisSerializer()));
}
}
I've been writting some tests for a legacy web app on java using DeltaSpike, Weld, Hibernate and others frameworks.
I have faced some problem with my first test class that injects many Mocked interfaces on a Service.
Let me show some code:
Service to be tested
public class DistribuicaoProcessoManualServiceImpl extends DistribuicaoService implements DistribuicaoProcessoManualService {
#Inject
#WebServiceTJDBEntityManager EntityManager wstjEM;
private ForoTJComarcaMPRepository foroMPRepository;
private AssuntoTJNaturezaMPRepository naturezaMPRepository;
private VaraTJVaraMPRepository varaMPRepository;
private ClasseTJTipoMPRepository tipoMPRepository;
private ProcessoRepository processoRepository;
private UsuarioRepository usuarioRepository;
private UsuarioDaSessao usuarioDaSessao;
/**
* #deprecated CDI eyes only
*/
public DistribuicaoProcessoManualServiceImpl() {
this(null, null, null, null, null, null, null);
}
#Inject
public DistribuicaoProcessoManualServiceImpl(
ForoTJComarcaMPRepository foroMPRepository,
AssuntoTJNaturezaMPRepository naturezaMPRepository,
ClasseTJTipoMPRepository tipoMPRepository,
ProcessoRepository processoRepository,
UsuarioRepository usuarioRepository,
UsuarioDaSessao usuarioDaSessao,
VaraTJVaraMPRepository varaMPRepository) {
this.foroMPRepository = foroMPRepository;
this.naturezaMPRepository = naturezaMPRepository;
this.tipoMPRepository = tipoMPRepository;
this.processoRepository = processoRepository;
this.usuarioRepository = usuarioRepository;
this.usuarioDaSessao = usuarioDaSessao;
this.varaMPRepository = varaMPRepository;
}
#Override
#Transactional(readOnly = false, qualifier = {WebServiceTJDBEntityManager.class})
public Processo vinculaOuPreparaParaEspecializacao(Processo processo) {
//Service do some validations here with Guava's Preconditions;
Usuario usuario = usuarioRepository.procurarPorLogin(usuarioDaSessao.getUsuario().getLogin());
processo.atualizaInformacoesDeProcuradoriaEUsuario(usuario);
ProcessoDoTJMapeamentoParaMP processoDePara = compoeMapeamento(processo);
VaraTJVaraMP varaMP = varaMPRepository.procurarPorIdVaraTJForoEPorProcuradoria(processoDePara);
ForoTJComarcaMP comarcaMP = foroMPRepository.procurarPorIdForoEPorProcuradoria(processoDePara);
AssuntoTJNaturezaMP naturezaMP = naturezaMPRepository.procurarPorAssuntoEPorProcuradoria(processoDePara);
ClasseTJTipoMP tipoMP = tipoMPRepository.procurarPorCodigoEPorProcuradoria(processoDePara);
processoDePara
.comComarcaMP(comarcaMP)
.comVaraMP(varaMP)
.comNaturezaMP(naturezaMP)
.comTipoMP(tipoMP);
processoRepository.inclui(processo);
return processo;
}
}
The extended Class:
public abstract class DistribuicaoService {
public ProcessoDoTJMapeamentoParaMP compoeMapeamento(Processo processo) {
return new ProcessoDoTJMapeamentoParaMP(processo);
}
}
The mapper/builder/aggregator:
public class ProcessoDoTJMapeamentoParaMP implements Serializable {
private static final long serialVersionUID = 1L;
private final Processo processo;
public ProcessoDoTJMapeamentoParaMP(final Processo processo) {
this.processo = processo;
this.comCamaraMP( OrgaoJulgadorTJCamaraMP.semEfeito() )
.comRelatorMP( RelatorTJRelatorMP.semEfeito() )
.comOrigemMP( new OrgaoJulgadorTJOrigemMP() )
.comTipoDeRemessaMP();
}
public ProcessoDoTJMapeamentoParaMP comComarcaMP(ComarcaMP comarcaMP) {
processo.getDadosOrigem().setCodigoComarcaMP(comarcaMP.getIdComarca());
return this;
}
public ProcessoDoTJMapeamentoParaMP comVaraMP(VaraMP varaMP) {
processo.getDadosOrigem().setCodigoVaraMP(varaMP.getIdVaraMP());
return this;
}
public ProcessoDoTJMapeamentoParaMP comNaturezaMP(AssuntoTJNaturezaMP naturezaMP) {
processo.getAssuntoPrincipal().setCodigoNaturezaMP(naturezaMP.getIdNatureza());
return this;
}
public ProcessoDoTJMapeamentoParaMP comTipoMP(ClasseTJTipoMP tipoMP) {
processo.getDadosProcesso().getClasse().setCodigoTipoMP(tipoMP.getIdTipo());
return this;
}
ProcessoDoTJMapeamentoParaMP comCamaraMP(OrgaoJulgadorTJCamaraMP camaraMP) {
processo.getDadosDistribuicao().getMapeamento().setCodigoCamaraMP(camaraMP.getIdCamara());
return this;
}
ProcessoDoTJMapeamentoParaMP comRelatorMP(RelatorTJRelatorMP relatorMP) {
processo.getDadosDistribuicao().getMapeamento().setCodigoRelatorMP(relatorMP.getIdRelatorMP());
return this;
}
ProcessoDoTJMapeamentoParaMP comOrigemMP(OrgaoJulgadorTJOrigemMP origemMP) {
processo.getDadosDistribuicao().getMapeamento().setCodigoOrigemMP(origemMP.getIdOrigem());
return this;
}
ProcessoDoTJMapeamentoParaMP comTipoDeRemessaMP() {
processo.setTipoRemessa(TipoDeRemessa.fromTipoDeProcesso(this.processo.getProcessoVirtualTJ()));
return this;
}
public Procuradoria getProcuradoria() {
return processo.getProcuradoria();
}
public Integer getCodigoForoTJ() {
return processo.getDadosOrigem().getCodigoForoPrimeiraInstancia();
}
public Integer getCodigoVaraTJ() {
return processo.getDadosOrigem().getCodigoVaraPrimeiraInstancia();
}
public List<Parte> getPartes() {
return processo.getPartes();
}
public String getNomeAssuntoTJ() {
return processo.getAssuntoPrincipal().getDescricaoAssunto();
}
public Integer getCodigoClasseTJ() {
return processo.getDadosProcesso().getClasse().getCodigoClasse();
}
public String getNomeOrgaoJulgadorTJ() {
return processo.getDadosDistribuicao().getOrgaoJulgador().getNomeOrgaoJulgador();
}
public String getNomeRelatorTJ() {
return processo.getDadosDistribuicao().getRelator().getNomeRelator();
}
public Integer getIdAssuntoTJ() {
return processo.getAssuntoPrincipal().getCodigoAssunto();
}
public Movimentacao getUltimoMovimento() {
return null;
}
Class for Test:
#SuppressWarnings("deprecation")
#RunWith(MockitoJUnitRunner.class)
public class DistribuicaoProcessoManualServiceTest {
#Mock private ForoTJComarcaMPRepository foroMPRepository;
#Mock private AssuntoTJNaturezaMPRepository naturezaMPRepository;
#Mock private VaraTJVaraMPRepository varaMPRepository;
#Mock private ClasseTJTipoMPRepository tipoMPRepository;
#Mock private ProcessoRepository processoRepository;
#Mock private UsuarioRepository usuarioRepository;
#Mock private Usuario usuario;
#Mock private Procuradoria procuradoria;
#Mock private VaraTJVaraMP varaMP;
#Mock private ForoTJComarcaMP comarcaMP;
#Mock private AssuntoTJNaturezaMP naturezaMP;
#Mock private ClasseTJTipoMP tipoMP;
#Mock private UsuarioDaSessao usuarioDaSessao;
#InjectMocks
private DistribuicaoProcessoManualServiceImpl service = new DistribuicaoProcessoManualServiceImpl();
private Processo processo;
#Before
public void setUpMethod() {
initMocks(this);
//Others Builders for populate "processo" here;
processo = ProcessoBuilder()
.com(hoje)
.com(PARECER)
.com(FISICO)
.com(dadosProcesso)
.com(dadosOrigem)
.com(distribuicao)
.com(fila)
.cria();
ProcessoDoTJMapeamentoParaMP mapeamento = new ProcessoDoTJMapeamentoParaMP(processo);
when(usuario.getLogin()).thenReturn("luizrodriguesj");
when(usuario.getProcuradoria()).thenReturn(procuradoria);
when(usuarioDaSessao.getUsuario()).thenReturn(usuario);
when(usuarioRepository.procurarPorLogin(anyString())).thenReturn(usuario);
when(comarcaMP.getIdComarca()).thenReturn(1);
when(foroMPRepository.procurarPorIdForoEPorProcuradoria(mapeamento)).thenReturn(comarcaMP);
when(varaMP.getIdVaraMP()).thenReturn(1);
when(varaMPRepository.procurarPorIdVaraTJForoEPorProcuradoria(mapeamento)).thenReturn(varaMP);
when(naturezaMP.getIdNatureza()).thenReturn(1);
when(naturezaMPRepository.procurarPorAssuntoEPorProcuradoria(mapeamento)).thenReturn(naturezaMP);
when(tipoMP.getIdTipo()).thenReturn(1);
when(tipoMPRepository.procurarPorCodigoEPorProcuradoria(mapeamento)).thenReturn(tipoMP);
}
Method with problem:
#Test(expected = ApplicationException.class)
public void naoPermitirDistribuicaoDeProcessoSemUmMapeamentoDeVaraCorrespondente() {
service.vinculaOuPreparaParaEspecializacao(processo);
}
The interface that it was possible to mock:
public interface UsuarioRepository extends GenericDAO<Usuario, Long> {
boolean isAutenticavel(Usuario usuario);
Usuario procurarPorLogin(String login);
List<Usuario> lista(UsuarioPesquisa pesquisa, Paginacao paginacao);
}
One of Interfaces that not obey instruction mock and return null:
public interface ForoTJComarcaMPRepository extends GenericDAO<ForoTJComarcaMP, Long> {
ForoTJComarcaMP procurarPorIdForoEPorProcuradoria(ProcessoDoTJMapeamentoParaMP processoDePara);
List<ForoTJComarcaMP> lista(DominioMPPesquisa pesquisa, Paginacao paginacao);
ForoTJComarcaMP procuraPorForoTJ(ForoTJComarcaMP foroTJComarcaMP);
ForoTJComarcaMP procuraPorEntidade(ForoTJComarcaMP clone);
List<ForoTJComarcaMP> listaMapeamentoDistinctPor(Procuradoria procuradoria);
}
After others methods in this class that runs without any problem, this last one just fails because a NullPointerException (NPE) that occurs in:
VaraTJVaraMP varaMP = varaMPRepository.procurarPorIdVaraTJForoEPorProcuradoria(processoDePara);
AssuntoTJNaturezaMP naturezaMP = naturezaMPRepository.procurarPorAssuntoEPorProcuradoria(processoDePara);
ClasseTJTipoMP tipoMP = tipoMPRepository.procurarPorCodigoEPorProcuradoria(processoDePara);
ForoTJComarcaMP comarcaMP = foroMPRepository.procurarPorIdForoEPorProcuradoria(processoDePara);
....
// The references "comarcaMP", "varaMP", "naturezaMP", "tipoMP" are null here and next step throws a NPE.
processoDePara
.comComarcaMP(comarcaMP)
Other Mocked Interface declared work without problem, like this one:
Usuario usuario = usuarioRepository.procurarPorLogin(usuarioDaSessao.getUsuario().getLogin());
Where the "usuario" reference is setted as declared on setup method in Test Class.
Sorry for any mistake or lack of more informations.
Thanks and best regards!
I am trying to mock convertors method using 'when---thenReturn'
In my serviceTest file but still its throwing null pointer exception.
Is there any good way to mock convertor?
Thanks in advance.
For examples, you can refer to OOTB Test classes. (Note: The classes uses given-willReturn, but you can adjust it for when-thenReturn. These are just different approaches to testing using Mockito)
If you are looking for a Converter testing its attribute values, check de.hybris.platform.commercefacades.user.converters.populator.AddressPopulatorTest.
#UnitTest
public class AddressPopulatorTest
{
private AbstractPopulatingConverter<AddressModel, AddressData> addressConverter;
private final AddressPopulator addressPopulator = new AddressPopulator();
#Mock
private Map<String, Converter<AddressModel, StringBuilder>> addressFormatConverterMap;
#Mock
private Converter<AddressModel, StringBuilder> defaultAddressFormatConverter;
#Before
public void setUp()
{
MockitoAnnotations.initMocks(this);
addressPopulator.setAddressFormatConverterMap(addressFormatConverterMap);
addressPopulator.setDefaultAddressFormatConverter(defaultAddressFormatConverter);
addressConverter = new ConverterFactory<AddressModel, AddressData, AddressPopulator>().create(AddressData.class,
addressPopulator);
}
#Test
public void testConvert()
{
final AddressModel addressModel = mock(AddressModel.class);
final PK pk = PK.parse("123");
final TitleModel titleModel = mock(TitleModel.class);
final CountryModel countryModel = mock(CountryModel.class);
given(addressModel.getPk()).willReturn(pk);
given(addressModel.getBillingAddress()).willReturn(Boolean.TRUE);
given(addressModel.getShippingAddress()).willReturn(Boolean.TRUE);
given(addressModel.getTitle()).willReturn(titleModel);
given(addressModel.getFirstname()).willReturn("firstName");
given(addressModel.getLastname()).willReturn("lastname");
given(titleModel.getName()).willReturn("titleName");
given(titleModel.getCode()).willReturn("titleCode");
given(addressModel.getCompany()).willReturn("companyName");
given(addressModel.getLine1()).willReturn("line1");
given(addressModel.getLine2()).willReturn("line2");
given(addressModel.getTown()).willReturn("town");
given(addressModel.getPostalcode()).willReturn("postalCode");
given(addressModel.getPhone1()).willReturn("phone");
given(addressModel.getEmail()).willReturn("email");
given(addressModel.getCountry()).willReturn(countryModel);
given(countryModel.getIsocode()).willReturn("countryCode");
given(countryModel.getName()).willReturn("countryName");
given(defaultAddressFormatConverter.convert(Mockito.any(AddressModel.class))).willReturn(
new StringBuilder("singleLineAddress"));
final AddressData addressData = addressConverter.convert(addressModel);
Assert.assertEquals("123", addressData.getId());
Assert.assertTrue(addressData.isBillingAddress());
Assert.assertTrue(addressData.isShippingAddress());
Assert.assertEquals("titleName", addressData.getTitle());
Assert.assertEquals("titleCode", addressData.getTitleCode());
Assert.assertEquals("firstName", addressData.getFirstName());
Assert.assertEquals("lastname", addressData.getLastName());
Assert.assertEquals("companyName", addressData.getCompanyName());
Assert.assertEquals("line1", addressData.getLine1());
Assert.assertEquals("line2", addressData.getLine2());
Assert.assertEquals("town", addressData.getTown());
Assert.assertEquals("postalCode", addressData.getPostalCode());
Assert.assertEquals("phone", addressData.getPhone());
Assert.assertEquals("email", addressData.getEmail());
Assert.assertEquals("countryCode", addressData.getCountry().getIsocode());
Assert.assertEquals("countryName", addressData.getCountry().getName());
}
}
If you are looking for a Facade that is using a Converter, check de.hybris.platform.commercefacades.customer.impl.DefaultCustomerFacadeTest
#UnitTest
public class DefaultCustomerFacadeTest
{
private static final String TEST_DUMMY = "dummy";
private static final String TEST_OLD_PASS = "oldPass";
private static final String TEST_NEW_PASS = "newPass";
private static final String TEST_USER_UID = "testUid";
private static final String TEST_TOKEN = "token";
private DefaultCustomerFacade defaultCustomerFacade;
#Mock
private UserService userService;
#Mock
private UserModel user;
#Mock
private CustomerAccountService customerAccountService;
#Mock
private ModelService mockModelService;
#Mock
private AbstractPopulatingConverter<AddressModel, AddressData> addressConverter;
#Mock
private AbstractPopulatingConverter<UserModel, CustomerData> customerConverter;
#Mock
private AddressReversePopulator addressReversePopulator;
#Mock
private AbstractPopulatingConverter<CreditCardPaymentInfoModel, CCPaymentInfoData> creditCardPaymentInfoConverter;
#Mock
private CommonI18NService commonI18NService;
#Mock
private StoreSessionFacade storeSessionFacade;
#Mock
private CartService cartService;
#Mock
private CommerceCartService commerceCartService;
#Mock
private UserFacade userFacade;
#Mock
private SessionService sessionService;
#Mock
private OrderFacade orderFacade;
#Mock
private CartCleanStrategy cartCleanStrategy;
private CustomerModel customerModel;
private CustomerModel guestCustomerModel;
private AddressModel addressModel;
private AddressModel addressModel2;
private AddressData addressData;
private CreditCardPaymentInfoModel creditCardPaymentInfoModel;
private CCPaymentInfoData ccPaymentInfoData;
private CustomerNameStrategy customerNameStrategy;
private CurrencyData defaultCurrencyData;
private LanguageData defaultLanguageData;
protected static class MockAddressModel extends AddressModel
{
private final long id;
public MockAddressModel(final long id)
{
this.id = id;
}
#Override
public PK getPk()
{
return de.hybris.platform.core.PK.fromLong(id);
}
}
#Before
public void setUp()
{
MockitoAnnotations.initMocks(this);
defaultCustomerFacade = new DefaultCustomerFacade();
defaultCustomerFacade.setUserService(userService);
defaultCustomerFacade.setModelService(mockModelService);
defaultCustomerFacade.setCustomerAccountService(customerAccountService);
defaultCustomerFacade.setAddressConverter(addressConverter);
defaultCustomerFacade.setCustomerConverter(customerConverter);
defaultCustomerFacade.setAddressReversePopulator(addressReversePopulator);
defaultCustomerFacade.setCreditCardPaymentInfoConverter(creditCardPaymentInfoConverter);
defaultCustomerFacade.setCommonI18NService(commonI18NService);
defaultCustomerFacade.setStoreSessionFacade(storeSessionFacade);
defaultCustomerFacade.setCartService(cartService);
defaultCustomerFacade.setCommerceCartService(commerceCartService);
defaultCustomerFacade.setUserFacade(userFacade);
defaultCustomerFacade.setSessionService(sessionService);
defaultCustomerFacade.setOrderFacade(orderFacade);
defaultCustomerFacade.setCartCleanStrategy(cartCleanStrategy);
customerNameStrategy = new DefaultCustomerNameStrategy();
defaultCustomerFacade.setCustomerNameStrategy(customerNameStrategy);
addressModel = new MockAddressModel(9999L);
addressModel2 = new MockAddressModel(8888L);
addressData = new AddressData();
addressData.setId("9999");
customerModel = new CustomerModel();
customerModel.setDefaultShipmentAddress(addressModel2);
creditCardPaymentInfoModel = new CreditCardPaymentInfoModel();
final List<CreditCardPaymentInfoModel> creditCards = new ArrayList<CreditCardPaymentInfoModel>();
creditCards.add(creditCardPaymentInfoModel);
ccPaymentInfoData = new CCPaymentInfoData();
guestCustomerModel = new CustomerModel();
guestCustomerModel.setUid(TEST_USER_UID + "|" + TEST_DUMMY);
guestCustomerModel.setDefaultShipmentAddress(addressModel);
guestCustomerModel.setDefaultPaymentAddress(addressModel2);
given(addressConverter.convert(addressModel)).willReturn(addressData);
given(creditCardPaymentInfoConverter.convert(creditCardPaymentInfoModel)).willReturn(ccPaymentInfoData);
given(userService.getCurrentUser()).willReturn(customerModel);
given(customerAccountService.getAddressForCode(customerModel, "9999")).willReturn(addressModel);
given(customerAccountService.getCreditCardPaymentInfos(customerModel, true)).willReturn(creditCards);
given(customerAccountService.getCreditCardPaymentInfoForCode(customerModel, "code")).willReturn(creditCardPaymentInfoModel);
given(mockModelService.create(CustomerModel.class)).willReturn(new CustomerModel());
defaultCurrencyData = new CurrencyData();
defaultCurrencyData.setIsocode("GBP");
defaultLanguageData = new LanguageData();
defaultLanguageData.setIsocode("en");
given(storeSessionFacade.getDefaultCurrency()).willReturn(defaultCurrencyData);
given(storeSessionFacade.getDefaultLanguage()).willReturn(defaultLanguageData);
}
I want to write a test to test my WebSocketHandlerDecorator, but I encouter some problems.
here is the error:
java.lang.IllegalArgumentException: Delegate must not be null
at org.springframework.util.Assert.notNull(Assert.java:193) at
org.springframework.web.socket.handler.WebSocketHandlerDecorator.(WebSocketHandlerDecorator.java:42)
import org.springframework.util.Assert;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;
public class MyWebSocketHandlerDecorator extends WebSocketHandlerDecorator {
public MySocketHandlerDecorator(WebSocketHandler delegate) {
super(delegate);
}
#Override
public void handleMessage(final WebSocketSession session, final WebSocketMessage<?> message) throws Exception {
final TextMessage MyMessage = (TextMessage) message;
super.handleMessage(session, MyMessage);
}
}
here is my test case:
public class MyWebSocketHandlerDecpratorTest {
#Mock
private WebSocketSession session;
#Mock
WebSocketHandler delegate;
#Spy
private WebSocketHandlerDecorator webSocketHandlerDecorator = new WebSocketHandlerDecorator(delegate);
#InjectMocks
MyWebSocketHandlerDecorator myWebSocketHandlerDecorator;
private TextMessage message;
#Before
public void set_up(){
MockitoAnnotations.initMocks(this);
message = new TextMessage("Test Message".getBytes());
}
#Test
public void handleMessage()throws Exception{
myWebSocketHandlerDecorator.handleMessage(session, message);
verify(webSocketHandlerDecorator, times(1)).handleMessage(session, message);
}
}
Can anyone help me correct my test and figure out what issue it has?
public WebSocketHandlerDecorator(WebSocketHandler delegate) {
Assert.notNull(delegate, "Delegate must not be null");
this.delegate = delegate;
}
You have to setup your #Spy in the #Before method, because at the time the class is created, the mocks are not yet initialized:
public class MyWebSocketHandlerDecpratorTest {
#Mock
private WebSocketSession session;
#Mock
WebSocketHandler delegate;
private WebSocketHandlerDecorator webSocketHandlerDecorator;
#InjectMocks
MyWebSocketHandlerDecorator myWebSocketHandlerDecorator;
private TextMessage message;
#Before
public void set_up(){
MockitoAnnotations.initMocks(this);
webSocketHandlerDecorator = Mockito.spy(new WebSocketHandlerDecorator(delegate));
message = new TextMessage("Test Message".getBytes());
}
#Test
public void handleMessage()throws Exception{
myWebSocketHandlerDecorator.handleMessage(session, message);
verify(webSocketHandlerDecorator, times(1)).handleMessage(session, message);
}
}