繁体   English   中英

在Spring引导测试中,如何创建一个bean并通过@Autowired注入?

[英]In a Spring boot test, how can I create a bean and injects by @Autowired?

当我测试Spring Boot服务时,我不知道如何注入@Autowired bean。

我的bean(Spring从application.yml填充@Value):

@Component
public class NavigatorProperties {
    @Value("${timerDelay}")
    private String timerDelay;

    public String getTimerDelay() {
        return timerDelay;
    }
    public void setTimerDelay(String timerDelay) {
        this.timerDelay = timerDelay;
    }
}

我的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());
        ...
    }
}

这可以正常工作,并且int值正确。 这是我的测试:

@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
    }

在此测试注释中,我如何通过@Autowired注入ListenerApi?

谢谢。

首先,您需要使用org.springframework.stereotype.Component注释依赖项。

@Component
public class ListenerApi implements IRestListenerApi {

然后将其注入所需的任何位置:

@Autowired
private ListenerApi listenerApi;

您的@SpringBootTest应该像这样:

@SpringBootTest(classes = {ListenerApi.class, NavigatorProperties.class})

包括要注入到ListenerApiTest中的每个bean类

在要扫描的软件包中添加组件扫描注释

@ComponentScan(basePackages = "my.package.to.scan")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM