我開始與Spring框架合作,並試圖圍繞bean概念進行包裝。 我有一個XML文件:春豆價值注入
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id= "currentDateService" class ="xx.CurrentDateSerivceimpl" />
</beans>
而一個類來獲得當前日期:
public class CurrentDateServiceImpl implements CurrentDateService {
public LocalDate getCurrentDate() {
return LocalDate.now() ;
}
我試圖做到的是一個簡單的@Test斷言如果bean值是與我提供的當前日期相同。
什麼我被困在是:
@Test
public void test() {
ApplicationContext context = new ClassPathXmlApplicationContext("application-context.xml");
CurrentDateServiceImpl currentDateServiceObj = (CurrentDateServiceImpl) context.getBean("currentDateService");
LocalDate date = LocalDate.now();
LocalDate date2 = "the value of the bean";
assertEquals(date, date2);
}
,我不知道我怎麼可以給測試提供bean的價值,我想知道如何完成它,如果有除了春天文檔本身任何好的教程/單證
編輯:
package lt.insoft.app.bl.service.impl;
import static org.junit.Assert.assertEquals;
import java.time.LocalDate;
import lt.insoft.app.bl.service.CurrentDateService;
import lt.insoft.app.bl.service.CurrentDateServiceFormat;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "file:src/main/resources/META-INF/application-context.xml" })
public class CurrentDateServiceImplTest {
@Autowired
CurrentDateService service;
CurrentDateServiceFormat service2;
@Test
public void test() {
LocalDate date = LocalDate.now();
LocalDate date2 = service.getCurrentDate();
String date3 = service2.formatCurrentDate();
System.out.println(date3);
assertEquals(date, date2);
}
}
這是爲什麼不打印格式化的日期?
只需調用'currentDateServiceObj.getCurrentDate()' – Jens 2014-10-06 05:24:11
有沒有必要用手工做的一切。對於新代碼,我通常推薦使用JavaConfig over XML,當然也可以注入bean查找。 – chrylis 2014-10-06 06:01:53