I am facing a strange problem while trying to unit test my code.
Here is my code :
public class ItemService {
private OfferService offerService;
@Inject
public ItemService (OfferService offerService){
this.offerService = offerService;
}
public List<Item> buildItems(ItemInfo itemInfo) {
List<Item> items = processItem(itemInfo);
Offers<Offer> offers = fetchItemInfo(items);
// based on the object offers, do some processing
}
private Offers<Offer> fetchItemInfo(List<Item> items) {
Offers<Offer> offers = new Offers<>();
// some processing here with offers.
// calling the db to fetch details
offerService.fetchInfoFromDB(offers);
return offers;
}
}
public class OfferService {
public void fetchInfoFromDB(Offers<Offer> offers) {
// fetching details from DB
// and updating the object **offers**
// myDao.getDetailsById(id);
}
}
Now I have written junit to test the method buildItems()
UPDATE updating the mocks used
@RunWith(PowerMockRunner.class)
@PrepareForTest(ItemService.class)
public class ItemServiceTest{
@Mock private MyDAO myDao;
@Mock private OfferService offerService;
@Before
public void setUp() throws Exception {
ItemService itemService = new ItemService ();
}
public void testBuildItems(){
// some code -----
itemInfo = buildItemInfo();
offerDetail = buildOfferDetail();
when(myDao.getDetailsById(Mockito.anyLong())).thenReturn(offerDetail);
// some code -----
List<Item> items = itemService.buildItems(itemInfo);
Assert.assertNotNull(items);
}
}
I am running with coverage and I can see that the below line got executed but the actual method is not getting called :
offerService.fetchInfoFromDB(offers);
I am getting null values in offers. Then I added the below line :
doCallRealMethod().when(offerService).fetchInfoFromDB(offers);
Still the same result. The offers object is passed by reference and is getting updated after the DB call which I am mocking already. But upto that call my code is not reaching. How can I update the offers object in my junit. Please help.
CodePudding user response:
Can you please tell what your List<Item> items = processItem(itemInfo)
returning while you debug? Secondly offerService is a dependency in the class but i dont see it being injected or initialized.
CodePudding user response:
Your test is calling a zero arg ItemService()
constructor, not the one arg @Inject
constructor you posted. Either your code won't compile, or you haven't actually shown us the code in question.
Also, you say you are mocking offerService
:
- You call
when
onmyDao
and notofferService
, - you do not pass your mock
offerService
into yourItemService
constructor, as innew ItemService(offerService)
, and - your
doCallRealMethod
won't work because your mockofferService
won't use your mockmyDao
; you'll need to mock the call onofferService
directly with athenAnswer
that changes the passedList<Offer>
, as on my question you linked.
If you fix those three you will be considerably closer to a working test.