繁体   English   中英

无法使用Java注释跨各种类对TestNG使用spring依赖项注入(JSR 330标准注释)

[英]Not able to use spring dependency injection across various classes for TestNG using java annotations(JSR 330 Standard Annotations)

我有一项服务,试图在测试中跨各种类注入服务,但我将其实例作为null。

我的配置界面:

MyService.java

public interface MyService {

    public String getHostUri();

}

该接口的实现类: MyServiceImpl.java

public class MyServiceImpl implements MyService {

    private static final String BASE_HOST_URI_CONFIG = "localhost:4444";

    @Override
    public String getHostUri() {
        return BASE_HOST_URI_CONFIG;
    }

我的Spring配置类与bean:

@Configuration

public class AutomationSpringConfig {

    @Bean
    public MyService getMyService(){
        return new MyServiceImpl();
    }

}

我的testNG课:

@ContextConfiguration(classes=AutomationSpringConfig.class ,loader =AnnotationConfigContextLoader.class)

public class BasicAutomatedTest extends AbstractTestNGSpringContextTests {

    private static final Logger LOGGER = Logger.getLogger(BasicAutomatedTest.class);

    @Inject
    private MyService myService;


    @Test
    public void basicTest {
        Setup setup = new Setup();
        LOGGER.info(myService.getHostUri());
        LOGGER.info(setup.myService.getHostUri());

    }
}

我无法获得注射的助手班:

public class Setup {

  @Inject

  public MyService myService;

}

因此,当我尝试通过BasicAutomatedTest的basicTest方法中的设置对象获取hostUri时,我得到了NullPointerException。 因此,我无法将MyService bean注入Setup类。

为了使用注释,您需要在bean XML配置文件中指定该行为。 像这样:

<context:component-scan base-package="your.base.package"/>
<context:annotation-config/>

希望能帮助到你!

暂无
暂无

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

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