Reputation: 213
Earlier i had the implemenation like:
public class FeedbackService {
private final FeedbackHelper feedbackHelper;
@Inject
public FeedbackService(FeedbackHelper feedbackHelper) {
this.feedbackHelper = feedbackHelper;
}
//rest of the class
}
Test file
public class FeedbackDataServiceTest {
private FeedbackService feedbackService;
@Mock private FeedbackHelper feedbackHelper;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
this.feedbackService = new FeedbackService(feedbackHelper);
}
}
It was workign fine. But when I changed to:
public class FeedbackService {
@Inject private FeedbackHelper feedbackHelper;
}
Test file
public class FeedbackDataServiceTest {
private FeedbackService feedbackService;
@Mock private FeedbackHelper feedbackHelper;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
}
}
The test cases started failing. Is anything else required to be done?
Upvotes: 2
Views: 188
Reputation: 2047
There are three types of injection. The suggestion is to use constructor injection if the dependency is mandatory and setter injection if it is optional.
You can use @InjectMock
on the under test object if you want to mock a field injection. But it is hard to test if you want to test without mocking framework.
@RunWith(MockitoJUnitRunner.class)
public class ApplicationTest
{
@InjectMocks
MainClass sut;
@Mock
DatabaseDAO dependentClassOne;
@Test
public void validateTest()
{
boolean saved = sut.save("abcd");
assertEquals(true, saved);
}
Upvotes: 2
Reputation: 1560
Use @InjectMocks
to inject the mocks into the Service class.
public class FeedbackDataServiceTest {
@InjectMocks private FeedbackService feedbackService;
@Mock private FeedbackHelper feedbackHelper;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
}
}
Upvotes: 2