user3659052 user3659052 - 1 month ago 15
Java Question

Mockito skip new object call

public void createId() {

Customer cust = findCustomer(this.custId);
Address addr = findAddress(this.addr);

UniqueIdCreator create = new UniqueIdCreator(this.custId, this.addr, this.name);
create.populate();
this.name.setName(create.customerName.getName());
}


for the above how do I skip method
create.populate();


Here is what I did:

@Test
public void test {
Customer cust = new Customer();
cust.setId(1);
cust.setName("test");
Address addr = new Address();
addr.setStreet("test-st");
IdCreator c = Mockito.spy(new IdCreator(cust,addr,null));
getDao.getPresist.add(cust);
getDao.getPresist.add(addr);
c.createId();
}


error: null pointer inside of method 'create.populate();'

This is for mockito only.

Answer

At a high level, you haven't written the code to be flexible enough for what you're asking for. createId's implementation, for better or worse, creates a new instance of UniqueIdCreator with exactly that behavior.

Though you could go with full dependency injection here and pass in a UniqueIdCreatorFactory, it may be much simpler to just extract the creation into an overridable method:

public void createId() {
    Customer cust = findCustomer(this.custId);
    Address addr = findAddress(this.addr);

    UniqueIdCreator create = makeIdCreator();
    this.name.setName(create.customerName.getName());
}

protected UniqueIdCreator makeIdCreator() {
    UniqueIdCreator create = new UniqueIdCreator(
        this.custId, this.addr, this.name);
    create.populate();
    return create;
}

This gives you all the opportunity you need to skip the implementation, without needing PowerMock or even Mockito:

@Test
public void test {
    Customer cust = new Customer();
    cust.setId(1);
    cust.setName("test");
    Address addr = new Address();
    addr.setStreet("test-st");
    IdCreator c = Mockito.spy(new IdCreator(cust,addr,null) {
      @Override protected UniqueIdCreator makeIdCreator() {
        return Mockito.mock(UniqueIdCreator.class);
      }
    });
    getDao.getPresist.add(cust);
    getDao.getPresist.add(addr);
    c.createId();
}

But, of course, you can use your Spy too:

@Test
public void test {
    Customer cust = new Customer();
    cust.setId(1);
    cust.setName("test");
    Address addr = new Address();
    addr.setStreet("test-st");
    IdCreator c = Mockito.spy(new IdCreator(cust,addr,null));
    doReturn(Mockito.mock(UniqueIdCreator.class)).when(c).makeIdCreator();
    getDao.getPresist.add(cust);
    getDao.getPresist.add(addr);
    c.createId();
}