單元測試使用spring註解獲取bean

在實際項目開發中經常會有單元測試,單元測試中經常會用類似這樣的代碼片段獲取spring管理的bean

1
2
3
4
5
@Test
public void testSendEmail(){
        MessageService messageService = (MessageService) BeanFactory.getInstance().getBean("messageService");
        messageService.send();
}

 這樣既不美觀,又比較繁瑣,spring引進了spring-test跟junit結合使用可以方便的得到spring bean

 因爲在項目中適用maven管理依賴,先在pom.xml中添加依賴

1
2
3
4
5
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>

 綁定spring配置文件路徑

複製代碼
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:applicationContext.xml" })
public class BaseTest extends TestCase {
    protected Logger logger = LoggerFactory.getLogger(getClass());

}
在單元測試類中集成 BaseTest

public class PostServiceTest extends BaseTest {
@Resource(name = "postService")
private PostService postService;


@Test
public void testQuery2LevelPostType() {
Map<Integer,Object> map= postService.query2LevelPostType();
System.out.println("data size:" + map.size());
  }
}

這樣就可以在單元測試中輕鬆獲取spring bean了,減少了繁瑣的代碼也增強了代碼的可讀性

 

博客園地址:http://www.cnblogs.com/weiguo21/p/3582920.html

複製代碼
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章