![](/img/trans.png)
[英]Problem with @Autowired in JUnit Test on a Spring MVC project
[英]Spring 4.07 Junit Test and Autowired
嗨,我正在使用Spring和CDI。 在單元測試中,我想測試使用@Autowired批注的類。 問題是如果我創建此類的實例並調用方法,則所有帶注釋的對象都為null。 注釋基本上是有效的。 只是我的單元測試沒有
這是我的單元測試。 在這里,自動布線的作品。 在我的測試中,我創建了DemoConsumerBean .class的實例,並調用方法requestJobsFromPublishedJobsApi,在這里,我還有一些自動裝配的聲明。 問題是所有實例都為空!
@RunWith(SpringJUnit4ClassRunner.class)
@ActiveProfiles("development")
@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, FirstbirdTestExecutionListener.class, FlywayTestExecutionListener.class })
@ContextConfiguration(locations = { "classpath:hibernate-spring.xml" })
@FlywayTest
public class DemoConsumerBeanTest extends AbstractJUnit4SpringContextTests {
@Autowired
private CustomerManager customerManager;
@Autowired
private DemoDetailsManager demoDetailsManager;
@Before
public void setup() {
CamelContext context = new DefaultCamelContext();
exchange = new DefaultExchange(context);
}
@Test
public void requestJobsFromPublishedJobsApiTest() throws NoSuchDataException {
DemoConsumerBean demoConsumerBean = new DemoConsumerBean();
customer = new Customer();
customer.setCustomerId(15);
customer = customerManager.getCustomerById(customer);
// This one works
DemoDetails demoDetails = demoDetailsManager.getDemoDetailsByCustomerId(customer);
demoConsumerBean.requestJobsFromPublishedJobsApi(exchange, customer);
PublishedJobs apiJobs = exchange.getIn().getBody(PublishedJobs.class);
assertNotNull(apiJobs);
}
}
public class DemoConsumerBean {
@Autowired
protected CustomerManager customerManager;
@Autowired
protected DemoDetailsManager demoDetailsManager;
@Autowired
protected MessageLogManager messageLogManager;
public void requestJobsFromPublishedJobsApi(Exchange exchange, Customer customer) throws NoSuchDataException {
//this one is null!
DemoDetails demoDetails = demoDetailsManager.getDemoDetailsByCustomerId(customer);
PublishedJobs jobs = null;
if (demoDetails == null || StringUtils.isBlank(demoDetails.getDemoApiUrl())) {
throw new NoSuchDataException("No demo data found for customer " + customer.getCustomerFirstbirdId());
}
....
}
}
在new DemoConsumerBean();
使用new
new DemoConsumerBean();
繞過春天,那是你的問題。
使用spring的DemoConsumerBean
實例(即在測試中自動裝配)或添加設置器,並使用它們在測試中的DemoConsumerBean
中“手動裝配”:
@Test
public void requestJobsFromPublishedJobsApiTest() throws NoSuchDataException {
DemoConsumerBean demoConsumerBean = new DemoConsumerBean();
demoConsumerBean.setCustomerManager(this.customerManager)
// etc
一些閱讀: Spring框架參考-IoC容器
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.