单元测试Spring 3数据库方法

时间:2010-10-06 07:51:32

标签: java unit-testing spring junit

我有抽象类来定义数据库方法,例如插入和更新,以及实现它的具体类。数据库配置(dataSource,DatabaseTarget等)在context.xml-file中定义为bean。

当我使用Spring 3 anotations

时,带有方法的数据库在Controller中工作
private AbsractClass a;

构造

@Autowired
public Controller(AbstractClass a) {
    this.a =a;
}

......和a。的吸气剂。

通过

调用数据库方法
getA().insertValues();

但我想为我的方法编写Junit测试。这种情况有什么例子吗?我用Google搜索了几个小时。

1 个答案:

答案 0 :(得分:1)

如果要在不触及数据库的情况下测试控制器方法(这是正确的方法),请创建一个扩展AbsractClass的新类,并将其作为参数传递给Controller类,例如:

CustomerController controller= new CustomerController(new InMemoryCustomerDao());
//call your actions and assert, all calls to the database will hit the InMemoryDao.

另一种方法是使用Mock Object如果你不想在你的项目中创建额外的假类,或者你需要声明这些参数被正确调用。