Reputation: 383
I'm attempting to mock a few method calls but unfortunately I keep getting null returned. Can you help me point out where I may be going wrong? I am using the when().thenReturn() and I feel like I mocked the return variable correctly. Many thanks in advance. I'm new to JUnit and Mockito so my apologies if I'm missing anything obvious.
ServiceTest.java
@IntegrationTest
public class ServiceTest extends TransactionalTest {
private HistoryService orderHistoryService;
private CMSSiteModel website;
@Mock
protected DefaultWebService orderDetailsServiceWrapper;
@Mock
protected WebsiteService websiteService;
@Before
public void setUp()
{
MockitoAnnotations.initMocks(this);
website = mock(CMSSiteModel.class);
}
@Test
public void testFindOrderDetailsByConfirmationNumber() {
when(websiteService.getCurrentSite()).thenReturn(website);
final ResponseType response = orderHistoryService.findOrderDetailsByConfirmationNumber(OrderTestUtils.CONFIRMATION_NUMBER, OrderTestUtils.LOCATION_NUMBER);
Assert.assertEquals("Incorrect Approver Name", OrderTestUtils.APPROVER_NAME, response.getApprovedByName());
}
and Service.java
public class HistoryService implements OrderHistoryService {
@Autowired
private WebsiteService websiteService;
@Override
public OrderDetailsServiceResponseType findOrderDetailsByConfirmationNumber(String confirmationNumber, String locationNumber) {
CMSSiteModel test = websiteService.getCurrentSite(); //returning null
odsrHeader.setSource(test.getOrderSource());
}
}
Upvotes: 1
Views: 982
Reputation: 40683
I think you are assuming that Mockito will automatically inject the WebsiteService
into the OrderHistoryService
. You need to annotate the OrderHistoryService
with @InjectMocks
before Mockito will do this. InjectMocks
will create a normal instance of the class and then attempt to fill its fields with any mocked or spy classes that have been created as part of the given test.
eg.
public class ServiceTest extends TransactionalTest {
@InjectMocks
HistoryService orderHistoryService;
@Mock
WebsiteService websiteService;
...
}
That websiteService
in the HistoryService
is not null
is worrying. It seems like some other injection is happening somewhere and you have ended up with two separate mocked website services. One in your test class and the other in HistoryService
. You seem to have left out a fair bit of the test classes so it's hard to be sure what is actually going on.
Upvotes: 1
Reputation: 13716
Here is my Answer : [Try to write unit test case in one class]
Make Sure websiteService
is @Mock
in the Service Class.
Upvotes: 0