gpt4 book ai didi

java - Spring 4.07 Junit 测试和 Autowiring

转载 作者:太空宇宙 更新时间:2023-11-04 14:25:18 25 4
gpt4 key购买 nike

嗨,我正在使用 Spring 和 CDI。在我的单元测试中,我想测试一个使用 @Autowired 注释的类。问题是,如果我创建此类的实例并调用方法,则所有带注释的对象均为空。基本上注释是有效的。只是在我的单元测试中它没有

这是我的单元测试。 Autowired 在这里起作用。在我的测试中,我创建了 DemoConsumerBean.class 的实例,并调用方法 requestJobsFromPublishedJobsApi ,这里我还有一些 Autowired 声明。问题是所有实例都是空的!

@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 绕过 spring,这是你的问题。

要么使用 spring 中的 DemoConsumerBean 实例(即在测试中 Autowiring ),要么添加 setter 并使用它们在测试中的 DemoConsumerBean 中“手动 Autowiring ”:

@Test
public void requestJobsFromPublishedJobsApiTest() throws NoSuchDataException {
DemoConsumerBean demoConsumerBean = new DemoConsumerBean();
demoConsumerBean.setCustomerManager(this.customerManager)
// etc

一些阅读:Spring framework reference - The IoC container

关于java - Spring 4.07 Junit 测试和 Autowiring ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26744962/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com