Spring 4.07 Junit测试和自动装配

时间:2014-11-04 21:02:02

标签: java spring junit junit4 autowired

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

这是我的单元测试。在这里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());
    }
....
}   

}

1 个答案:

答案 0 :(得分:0)

new中使用new DemoConsumerBean();绕过spring,这就是你的问题。

从spring使用DemoConsumerBean实例(即在测试中自动装配)或添加setter并使用它们在测试中DemoConsumerBean中“手动自动装配”:

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

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