如何使用 Mockito 进行与数据库交互相关的行为

发布于 2024-12-28 15:04:36 字数 143 浏览 3 评论 0原文

这几天我一直在网上寻找这个问题的简单答案。我现在希望有人能引导我走向正确的方向。我是一名软件实习生,目前从事 Enterprise Java Beans 工作。

另外,为了确定我有多困惑,我的头脑不接受嘲笑甚至存根作为测试你拥有或可能开发的东西的正确方法。

I have been searching the net for a simple answer to the question for a few days now. I now want someone to guide me in the right direction. I am a Software Trainee currently working on Enterprise Java Beans.

Also, to establish how confused I am, my mind just doesn't accept mocking and even stubbing as a proper way of testing what you have or may develop.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

时光匆匆的小流年 2025-01-04 15:04:36

我的头脑不接受嘲笑甚至存根作为正确的方式
测试您拥有或可能开发的内容

当您获得更多经验时,您将看到模拟/存根的价值。请记住,隔离测试是单元测试的核心。集成测试是另一回事。

单独进行单元测试是建立工作功能基线的好方法。

隔离测试的唯一方法是使用模拟/存根。否则,您的许多测试最终将不得不访问数据库(在标准 Web 应用程序中),更不用说您需要为每个测试连接完整的组件堆栈了。

考虑这样一种情况,您必须对高级控制器进行单元测试。该控制器使用一个服务,该服务使用 2 个 DAO。要测试控制器是否返回了正确的数据,您必须执行以下任一操作:

1) 仅模拟服务,告诉它等待调用并返回一些数据,然后断言返回了正确的数据。

2) 创建服务的实例。创建每个 DAO 的实例,配置它需要的任何内部内容。将 DAO 放入服务中。用数据填充您的数据库。

哪一个听起来需要更多工作?请记住,服务本身是单独测试的,DAO 也是如此。

此外,考虑到模拟/存根进行测试可以促进更简洁的设计。人们普遍认为,松散耦合、紧密集成的代码是一种很好的做事方式。考虑如何测试事物自然适合这种设计。

my mind just doesn't accept mocking and even stubbing as a proper way
of testing what you have or may develop

You will see as you gain more experience the value of mocking/stubbing. Keep in mind that testing in isolation is the bailiwick of unit-tests. Integration tests are another matter.

Unit testing things in isolation is a good way to establish a baseline of working functionality.

The only way to test in isolation is with mocks/stubs. Otherwise a lot of your tests would end up having to hit the database (in a standard webapp), not to mention you would need to wire up a full stack of components for every test.

Consider a situation where you have to unit test a high level controller. That controller uses a service, which uses 2 DAOs. To test that the controller returned the correct data, you have to either

1) Just mock the service, tell it to expect a call and return some data, and then assert that the correct data is returned.

or

2) Create an instance of the service. Create an instance of each DAO, configured any internal stuff it needs. PUt the DAOs in the service. Populate your database with data.

Which sounds like more work? Keep in mind that the service itself is tested in isolation, as are the DAOs.

Also, testing with mocking/stubbing in mind promotes a cleaner design. It is generally established that loosely coupled, tightly integrated code is a good way to do things. Thinking about how you are going to test things naturally lends itself to that design.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文