Reputation: 185
When I test my Spring boot service I don't know how I can inject an @Autowired bean.
My bean (Spring fills @Value from application.yml):
@Component
public class NavigatorProperties {
@Value("${timerDelay}")
private String timerDelay;
public String getTimerDelay() {
return timerDelay;
}
public void setTimerDelay(String timerDelay) {
this.timerDelay = timerDelay;
}
}
My api:
public class ListenerApi implements IRestListenerApi {
@Autowired
private NavigatorProperties np;
public String doSomething (...) { // This is my service method.
// Here np.getTimerDelay() will return application.yml value.
int timerDelay = Integer.decode(np.getTimerDelay());
...
}
}
This works fine and int value is correct. Here is my test:
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {ListenerApiTest.class, NavigatorProperties.class})
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class ListenerApiTest {
@Autowired
private NavigatorProperties np; // Can be autowired or a new Object.
// Object to test.
private ListenerApi listenerApi;
@Test
public void test01ForceNumberFormatException() {
np.setTimerDelay("NumberFormatException");
// Inyect into ListenerApi
}
@Test
public void test02ForceNullPointerException() {
np.setTimerDelay(null);
// Inyect into ListenerApi
}
In this test comments, how I can inyect into ListenerApi by @Autowired?
Thanks.
Upvotes: 0
Views: 1306
Reputation: 1
your @SpringBootTest should be like:
@SpringBootTest(classes = {ListenerApi.class, NavigatorProperties.class})
include every bean class that you want to inject into ListenerApiTest
Upvotes: 0
Reputation: 582
Add component scan annotation with the package to scan
@ComponentScan(basePackages = "my.package.to.scan")
Upvotes: 0
Reputation: 15854
First of all, you need to annotate your dependency with org.springframework.stereotype.Component
.
@Component
public class ListenerApi implements IRestListenerApi {
Then Inject it in wherever required :
@Autowired
private ListenerApi listenerApi;
Upvotes: 3