2012-03-29 119 views
0

我在Spring中创建Junit测试用例。Spring Junit测试问题

private static BeanFactory servicefactory = null; 
private static BookingProcessService bookingProcessService; 
@BeforeClass 
public static void setUpBeforeClass() throws Exception{ 
    try{ 
     String[] configFiles = {"applicationcontext-Service.xml","applicationcontext-Hibernate.xml","applicationContext-dao.xml"}; 
     ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext(configFiles); 
     servicefactory = (BeanFactory) appContext; 
     bookingProcessService = (BookingProcessService) servicefactory.getBean("bookingProcessService");    
    }catch (Exception e){ 
     e.printStackTrace(); 
    } 
} 

此处BookingProcessService是一个接口,其实现类是BookingProcessServiceImpl.java。 在spring配置文件中,没有为其定义的bean id。 有没有什么办法可以使用'bookingProcessService'来调用在我的测试方法中写在BookingProcessImp.java中的实际方法定义?

回答

0

如果你正在配置这个测试,我建议使用注解,将会更清楚。

通常在您的“applicationcontext-Service.xml”中必须有用Implementation定义的bean,并且是您将使用此类的接口的类。

因此,您不会将代码与实现耦合。

在这个例子中,简单的必须做下:

@Autowired 
private BookingProcessService bookingProcessService; 

从春季@Autowired会从你的XML配置“的ApplicationContext-service.xml中”做国际奥委会的注解。

+0

但是在“applicationcontext-Service.xml”中,没有为BookingProcessService定义的bean。那么如何获得BookingProcessService实现对象并为此编写测试用例呢? – Anand 2012-03-29 11:32:56

+0

如果你没有为Spring注入bean,那么你不能注入到另一个对象中。然后,您必须在测试中创建一个新实例,如 - BookingProcessService bookingProcessService = new BookingProcessServiceImpl(),然后您将在测试中拥有该实例。我建议你定义Spring可以做IOC,并且会有Singleton实例。 – 2012-04-03 06:07:41