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!
Related
Place that is complaining the error:
#Data
public class AluguelValorForm {
#Autowired
private ValorAluguelMultaService valorAluguelMultaService;
#NotNull #NotEmpty
private String idAluguel;
#NotNull
private Double valor;
public AluguelValor converter(AluguelValorRepository aluguelValorRepository, AluguelForm form ) {
Double valorAluguel = valorAluguelMultaService.valorAluguel(form);
return new AluguelValor(idAluguel,valorAluguel);
}
public AluguelValor update(String idAluguel,Double valor) {
AluguelValor aluguelValor = new AluguelValor();
aluguelValor.setId(idAluguel);
aluguelValor.setValor(valor);
return aluguelValor;
}
Repository:
#Repository
public interface AluguelValorRepository extends MongoRepository<AluguelValor, String> {
Aluguel getReferenceById(String id);
}
Place that I call the method in AluguelValorForm:
#PostMapping
//#CacheEvict(value = "listaDeTopicos",allEntries = true)
public void cadastrar(#RequestBody AluguelForm form) {
Optional<Carro> carro = carroRepository.findByPlaca(form.getPlaca_carro());
Optional<Cliente> cliente = clienteRepository.findByCpf(form.getCpf());
if(carro.isPresent() && cliente.isPresent()) {
Aluguel aluguel2 = form.converter(aluguelRepository);
aluguelRepository.save(aluguel2);
Double valorAluguel = valorAluguelMultaService.valorAluguel(form);
AluguelValor aluguelValor = aluguelValorForm.update(aluguel2.getId(), valorAluguel);
aluguelValorRepository.save(aluguelValor);
}
}
Problem solved. Apparently, it's not possible to #Autowired a class that doesn't have any bean, like my RentValue. That's why I got this error.
How to write unit test (via Junit) for MongoTemplate updateFirst() method ?
I have this service class:
#Service
public class TemplateServiceImpl implements TemplateService
{
#Resource
private TemplateRepository templateRepository;
#Resource
private MongoTemplate mongoTemplate;
#Override
public TemplateDto create(TemplateDto templateDto)
{
TemplateDto result;
templateDto.setDeleted(false);
result = templateRepository.insert(templateDto);
return result;
}
#Override
public boolean update(ObjectId id, TemplateDto templateDto)
{
if (templateDto != null)
{
Update update = new Update();
if (templateDto.getName() != null)
{
update.set("name", templateDto.getName());
}
if (templateDto.getTemplate() != null)
{
update.set("template", templateDto.getTemplate());
}
if (templateDto.isDeleted())
{
update.set("deleted", Boolean.TRUE);
}
update.set("lastUpdate", new Date());
return mongoTemplate.updateFirst(new Query(Criteria.where("_id").is(id)), update, "template")
.wasAcknowledged();
}
return false;
}
}
I want write unit test for update method . This is my relevant test class:
#ExtendWith(MockitoExtension.class)
class TemplateServiceImplTest
{
#InjectMocks
private static TemplateServiceImpl templateService;
#Mock
private static TemplateRepository templateRepository;
#Mock
private static MongoTemplate mongoTemplate;
private static TemplateDto templateDto;
private static List<TemplateDto> listOfTemplates;
private static String requestBody;
#BeforeAll
private static void setUp(){
templateDto = createTemplateDto();
listOfTemplates = createListOfTemplate();
requestBody = createRequesyBody();
}
#Test
void create()
{
when(templateRepository.insert(templateDto)).thenReturn(templateDto);
TemplateDto actualResult = templateService.create(TemplateServiceImplTest.templateDto);
assertThat(actualResult).isNotNull();
assertThat(actualResult).isInstanceOf(TemplateDto.class);
assertThat(actualResult.getId()).isEqualTo(templateDto.getId());
}
#Test
void update()
{
Update update = new Update();
/*
when(mongoTemplate.updateFirst(new Query(Criteria.where("_id").is(templateDto.getId().toString())) ,update , TemplateDto.class)).thenReturn(
UpdateResult.acknowledged());
*/
/*
given(mongoTemplate.updateFirst(new Query(Criteria.where("_id").is(templateDto.getId().toString())) ,update , TemplateDto.class));
*/
boolean actualResult = templateService.update(templateDto.getId(), templateDto);
assertThat(actualResult).isNotNull();
assertThat(actualResult).isTrue();
}
// other methods...
}
When I run test I get NPE for mongoTemplate at update method , I searched and I saw this 2 approach:
when(mongoTemplate.updateFirst(new Query(Criteria.where("_id").is(templateDto.getId().toString())) ,update , TemplateDto.class)).thenReturn(
UpdateResult.acknowledged());
Or
given(mongoTemplate.updateFirst(new Query(Criteria.where("_id").is(templateDto.getId().toString())) ,update , TemplateDto.class));
But none of them worked .
actually how to test MongoTemplate updateFirst method?
Thanks
How to write unit test (via Junit) for MongoTemplate updateFirst() method ?
I have this service class:
#Service
public class TemplateServiceImpl implements TemplateService
{
#Resource
private TemplateRepository templateRepository;
#Resource
private MongoTemplate mongoTemplate;
#Override
public TemplateDto create(TemplateDto templateDto)
{
TemplateDto result;
templateDto.setDeleted(false);
result = templateRepository.insert(templateDto);
return result;
}
#Override
public boolean update(ObjectId id, TemplateDto templateDto)
{
if (templateDto != null)
{
Update update = new Update();
if (templateDto.getName() != null)
{
update.set("name", templateDto.getName());
}
if (templateDto.getTemplate() != null)
{
update.set("template", templateDto.getTemplate());
}
if (templateDto.isDeleted())
{
update.set("deleted", Boolean.TRUE);
}
update.set("lastUpdate", new Date());
return mongoTemplate.updateFirst(new Query(Criteria.where("_id").is(id)), update, "template")
.wasAcknowledged();
}
return false;
}
}
I want write unit test for update method .
This is my relevant test class:
#ExtendWith(MockitoExtension.class)
class TemplateServiceImplTest
{
#InjectMocks
private static TemplateServiceImpl templateService;
#Mock
private static TemplateRepository templateRepository;
#Mock
private static MongoTemplate mongoTemplate;
private static TemplateDto templateDto;
private static List<TemplateDto> listOfTemplates;
private static String requestBody;
#BeforeAll
private static void setUp(){
templateDto = createTemplateDto();
listOfTemplates = createListOfTemplate();
requestBody = createRequesyBody();
}
#Test
void create()
{
when(templateRepository.insert(templateDto)).thenReturn(templateDto);
TemplateDto actualResult = templateService.create(TemplateServiceImplTest.templateDto);
assertThat(actualResult).isNotNull();
assertThat(actualResult).isInstanceOf(TemplateDto.class);
assertThat(actualResult.getId()).isEqualTo(templateDto.getId());
}
#Test
void update()
{
Update update = new Update();
/*
when(mongoTemplate.updateFirst(new Query(Criteria.where("_id").is(templateDto.getId().toString())) ,update , TemplateDto.class)).thenReturn(
UpdateResult.acknowledged());
*/
/*
given(mongoTemplate.updateFirst(new Query(Criteria.where("_id").is(templateDto.getId().toString())) ,update , TemplateDto.class));
*/
boolean actualResult = templateService.update(templateDto.getId(), templateDto);
assertThat(actualResult).isNotNull();
assertThat(actualResult).isTrue();
}
// other methods...
}
I mocked MongoTemplate like this:
#Mock
private static MongoTemplate mongoTemplate;
when I run test I get NPE for mongoTemplate at update method , I searched and I saw this 2 approach:
when(mongoTemplate.updateFirst(new Query(Criteria.where("_id").is(templateDto.getId().toString())) ,update , TemplateDto.class)).thenReturn(
UpdateResult.acknowledged());
// Or
given(mongoTemplate.updateFirst(new Query(Criteria.where("_id").is(templateDto.getId().toString())) ,update , TemplateDto.class));
But None of them worked! .
Thank you all .
I have class
public class CloneUserService {
private final UserRepository userRepository;
private final PersonRepository personRepository;
private final OrderRepository orderRepository;
public CloneUserService(UserRepository userRepository, PersonRepository personRepository, OrderRepository orderRepository) {
this.userRepository = userRepository;
this.personRepository = personRepository;
this.orderRepository = orderRepository;
}
public void createFromTemplate(String templateUserId) {
User templateUser = userRepository.getUserById(templateUserId);
Person templatePerson = personRepository.getPersonByUserId(templateUserId);
List<Order> templateOrders = orderRepository.getOrdersByUserId(templateUserId);
User newUser = cloneUserFromTemplate(templateUser);
newUser.setId("newId");
userRepository.save(newUser);
Person newPerson = clonePersonFromTemplate(templatePerson);
newPerson.setUser(newUser);
newPerson.setId("newId");
personRepository.save(newPerson);
for (Order templateOrder : templateOrders) {
Order newOrder = cloneOrderFromTemplate(templateOrder);
newOrder.setId("newId");
newOrder.setUSer(newUser);
orderRepository.save(newOrder);
}
}
private Order cloneOrderFromTemplate(Order templateOrder) {
//logic
return null;
}
private Person clonePersonFromTemplate(Person templatePerson) {
//logic
return null;
}
private User cloneUserFromTemplate(User templateUser) {
//logic
return null;
}
}
I need to test this method createFromTemplate.
I create this test. I create stabs for each repository and store saved object into this stub. And I add the additional method for getting this object for the assertion.
It works. But I have 2 problems:
My template object is mutable. It is not a big problem but it is a fact.
If I add new methods to repository interface I must implement it in stubs.
Mu question - How can I test cloned objects like theses from my example?
I don't use spring and H2DB or another in-memory database.
I have a MongoDB database.
If I use mockito I will not understand how to assert new objects in void method.
class CloneUserServiceTest {
private CloneUserService cloneUserService;
private UserRepositoryStub userRepository;
private PersonRepositoryStub personRepository;
private OrderRepositoryStub orderRepository;
#Before
public void setUp() {
User templateUser = new User();
Person templatePerson = new Person();
List<Order> templateOrders = Collections.singletonList(new Order());
userRepository = new UserRepositoryStub(templateUser);
personRepository = new PersonRepositoryStub(templatePerson);
orderRepository = new OrderRepositoryStub(templateOrders);
cloneUserService = new CloneUserService(userRepository, personRepository, orderRepository);
}
#Test
void createFromTemplate() {
cloneUserService.createFromTemplate("templateUserId");
User newUser = userRepository.getNewUser();
// assert newUser
Person newPerson = personRepository.getNewPerson();
// assert newPerson
Order newOrder = orderRepository.getNewOrder();
// assert newOrder
}
private static class UserRepositoryStub implements UserRepository {
private User templateUser;
private User newUser;
public UserRepositoryStub(User templateUser) {
this.templateUser = templateUser;
}
public User getUserById(String templateUserId) {
return templateUser;
}
public void save(User newUser) {
this.newUser = newUser;
}
public User getNewUser() {
return newUser;
}
}
private static class PersonRepositoryStub implements PersonRepository {
private Person templatePerson;
private Person newPerson;
public PersonRepositoryStub(Person templatePerson) {
this.templatePerson = templatePerson;
}
public Person getPersonByUserId(String templateUserId) {
return templatePerson;
}
public void save(Person newPerson) {
this.newPerson = newPerson;
}
public Person getNewPerson() {
return newPerson;
}
}
private static class OrderRepositoryStub implements OrderRepository {
private List<Order> templateOrders;
private Order newOrder;
public OrderRepositoryStub(List<Order> templateOrders) {
this.templateOrders = templateOrders;
}
public List<Order> getOrdersByUserId(String templateUserId) {
return templateOrders;
}
public void save(Order newOrder) {
this.newOrder = newOrder;
}
public Order getNewOrder() {
return newOrder;
}
}
}
In your scenario I would consider using mocking framework like Mockito.
Some main advantages:
Adding new methods to repository interface doesn't require implementing it in stubs
Supports exact-number-of-times and at-least-once verification
Allows flexible verification in order (e.g: verify in order what you want, not every single interaction)
Very nice and simple annotation syntax - #Mock, #InjectMocks, #Spy
Here is an example - maybe it will interest you:
// arrange
Warehouse mock = Mockito.mock(Warehouse.class);
//act
Order order = new Order(TALISKER, 50);
order.fill(warehouse); // fill will call remove() implicitly
// assert
Mockito.verify(warehouse).remove(TALISKER, 50); // verify that remove() method was actually called
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);
}