
在我们开发项目时,如果在开发过程中没有严格的代码测试. 然后我们的项目上线后将非常痛苦. 疼痛在哪里?各种错误修复!
也就是说,没有经过测试的代码,我们不能保证代码的质量. 因此,单元测试变得尤为重要.

Junit是Eclipse中内置的单元测试工具. 早期版本使用继承的TestCase来实现单元测试. Junit4可以使用注释来实现单元测试代码.


因为Spring需要先启动IOC容器才能使用,特别是在Spring中集成了与相关的配置,并且必须启动Spring才能执行junit 4 spring,因此我们必须在测试中添加papapa的Spring启动代码码. 这些代码看起来实际上是多余的
让我们看一下SpringTest工件,它允许您减少测试代码,使用批注来控制Spring的ioc容器的启动junit 4 spring,并减少测试代码.

不仅如此,我们还可以使用@ Resource,@ Autowired批注将对象注入Test类的成员变量中
package test.dao;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.marker.mushroom.beans.Menu;
import org.marker.mushroom.dao.IMenuDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* 单元测试
* @author marker
* @version 1.0
* @blog www.yl-blog.com
* @weibo http://t.qq.com/wuweiit
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:/config/spring/*.xml")
public class MenuDaoTest extends AbstractJUnit4SpringContextTests {
// 自动注入Dao对象
@Autowired IMenuDao menuDao;
@Test
public void test(){
Menu m = menuDao.findByName("文章管理");
Assert.assertNotNull("is null ", m);
}
}

注意: 需要导入Spring-test-x.x.x.jar包. Spring配置文件位于此处的源代码config / spring中. 请注意,我是一个Web项目.
Spring Test使单元测试变得简单. 这样的测试代码非常酷. 该项目已成为Spring必不可少的工具. 当然,当我们的项目发布时,请勿将此jar放在lib中. 最好使用Ant或Maven和其他项目构造工具来打包和部署项目.
本文来自电脑杂谈,转载请注明本文网址:
http://www.pc-fly.com/a/ruanjian/article-165886-1.html
虽然我们现在应该在军事上做好最坏的打算
现在谁有钱还放银行