Reputation: 1767
I have the following class (Condensed it to focus on issue instead of showing entire class):
@Component
public class ABCDEF {
private final Helper helper;
private final URI uri;
public ABCDEF(Helper helper, @Value("${endpoint.url}") URI uri) {
this.helper = helper;
this.uri = uri;
}
public void b(){
helper.toString();
}
}
For its test, I am looking to inject the mocks as follows but it is not working. The helper comes up as null and I end up having to add a default constructor to be able to throw the URI exception.
Please advice a way around this to be able to properly inject the mocks. Thanks.
@RunWith(JUnitMockitoRunner.class)
public class ABCDEFTest {
@Mock
private Helper helper;
@InjectMocks
private ABCDEF abcdef = new ABCDEF(
helper,
new URI("test")
);
// adding just to be able to throw Exception
public ABCDEFTest() throws URISyntaxException {
}
@Test
public void b() {
abcdef.b();
}
}
Note: Using Mockito version 1.10.19. Will need to stick to this version.
Upvotes: 3
Views: 5296
Reputation: 6391
This should work:
@RunWith(MockitoJUnitRunner.class)
public class ABCDEFTest {
@Mock
private Helper helper;
private ABCDEF abcdef;
@Before
public void setUp() throws URISyntaxException {
abcdef = new ABCDEF(
helper,
new URI("test")
);
}
@Test
public void b() {
abcdef.b();
}
}
Or, instead of using @RunWith
, you can initialize mock inside setUp
method:
public class ABCDEFTest {
private Helper helper;
private ABCDEF abcdef;
@Before
public void setUp() throws URISyntaxException {
helper = Mockito.mock(Helper.class);
abcdef = new ABCDEF(
helper,
new URI("test")
);
}
@Test
public void b() {
abcdef.b();
}
}
Upvotes: 1