[英]Spring @Autowired fields are null. I am using @AutoWired Fields in different class
这是我的班级代码,其中有@Autowired
字段:
测试
@ContextConfiguration("classpath:spring.xml")
public abstract class TestA extends AbstractTestNGSpringContextTests {
@Autowired
@Value("#{environment.username}")
public String username;
@Autowired
@Value("#{environment.password}")
public String password;
@Autowired
@Value("#{environment.passwordtoken}")
public String passwordToken;
}
这是我尝试使用上述String变量的另一个类
public class TestData extends TestA {
ForceApi api;
public void setApi() {
// Instantiating api by setting username and pwd
System.out.println("In getApi");
ApiConfig ac = new ApiConfig();
ac.setUsername(username);
ac.setPassword(passwordToken); ac.setLoginEndpoint("https://login.salesforce.com/services/Soap/u/34.0/");
api = new ForceApi(ac);
}
public void pTestData() {
setApi();
// Create test data for play group admin
String idSoql = "SELECT id FROM PlayGroup__c";
List<Map> mapResults = api.query(idSoql).getRecords();
}
}
并尝试使用以下类执行测试:
public class TestB extends TestA{
@Test(dataProvider="browsers")
public void test1(){
TestData td = new TestData();
td.pTestData();
}
}
请帮助我确定我在哪里做错了。 我在这行中得到了空指针异常:
List<Map> mapResults = api.query(idSoql).getRecords();
我自己解决了上述问题。
我在使用@Autowired字段的类中使用了@Service(“ testdata”)
@Service("testdata")
public class TestData extends TestA {
ForceApi api;
public void setApi() {
// Instantiating api by setting username and pwd
System.out.println("In getApi");
ApiConfig ac = new ApiConfig();
ac.setUsername(username);
ac.setPassword(passwordToken); ac.setLoginEndpoint("https://login.salesforce.com/services/Soap/u/34.0/");
api = new ForceApi(ac);
}
public void pTestData() {
setApi();
// Create test data for play group admin
String idSoql = "SELECT id FROM PlayGroup__c";
List<Map> mapResults = api.query(idSoql).getRecords();
}
}
并在TestB中进行如下更改
public class TestB extends TestA{
@Test(dataProvider="browsers")
public void test1(){
TestData td = (TestData )applicationContext.getBean("testdata");
td.pTestData();
}
}
并在spring.xml中添加了如下的bean
<bean id="testdata" class="data.TestData"/>
使用Null指针异常解决了我的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.