gpt4 book ai didi

java - Spring 3 数据库方法的单元测试

转载 作者:行者123 更新时间:2023-12-01 16:01:09 26 4
gpt4 key购买 nike

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

当我使用 Spring 3 注释时,数据库及其方法在 Controller 中工作

private AbsractClass a;

构造函数:

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

...还有一个 setter/getter 。

调用数据库方法是通过

getA().insertValues();

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

最佳答案

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

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

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

关于java - Spring 3 数据库方法的单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3870429/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com