单元测试Dababase应用程序 [英] Unit Testing Dababase Applications

查看:102
本文介绍了单元测试Dababase应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试进入TDD领域,并且正在艰难地测试我拥有的一些用户模型.我正在尝试测试模型的验证,业务需求如下:

I am trying to get in to the TDD realm, and I'm having a hard time unit testing a few user models I have. I'm trying to test the validation of my models, and the business requirements are as follows:

  1. > =需要6个字符的用户名
  2. > = 5个字符的密码,至少包含1个字母和数字
  3. 需要有效的电子邮件格式
  4. ...等等等等
  5. 数据库中不存在用户名和电子邮件

除5(要求数据库处于已知状态)外,所有要求都易于测试.我知道使用PHPUnit可以使用XML文件将数据库设置为已知状态,但是还有更好的方法吗?

All requirements are easily testable, except 5, which requires the database to be in a known state. I know that with PHPUnit I can set up my database to be in a known state using XML files, but is there a better way?

我想要的是数据库恢复到运行测试之前(即在开发过程中)的状态.我想我可以使用MySQL事务来回滚更改,或者我也可以使用两个单独的数据库,一个用于开发,一个用于测试.

What I want is for my database to revert back to the state it was in prior to running tests (i.e., during development). I suppose I could use MySQL transactions to rollback the changes, or I suppose I could also use two separate databases, one for development and one for testing.

我还读过一些地方,在单元测试中不使用实际的数据库连接,而是使用模拟数据.不太清楚它是如何工作的.

I also read somewhere to not use actual DB connections in unit tests, and instead use mock data. Not quite sure how that works.

有人可以向我解释一下我有哪些不同的选择,哪些是最好的路线?

Can someone explain to me the different options I have, and which are the best routes?

谢谢

我认为我将采用Ruby on Rails的方法,只是建立了3个独立的数据库,即生产,开发和测试.除非有人强烈反对.

I think I'm going to go with the Ruby on Rails approach and just set up 3 separate databases, production, development, and testing. Unless someone has a strong objection.

推荐答案

有人说不对数据库进行测试,而像我这样的人则说这是知道DAO代码是否正确的唯一途径.

Some people say don't test on a database, others like me say its the only way you'll know if your DAO code is good.

您需要的是两个数据库.一种用于测试,另一种用于开发.最佳实践是为您的单元测试创​​建一个通用的超类,以建立数据库(可能会初始化一个新的架构),然后所有数据库单元测试都将在该数据库中运行.您可以在以后清理它.

What you need is two database. One for testing and one for development. Best practice is to have a common superclass for your unit tests that sets up the database (perhaps inits a fresh schema) and then all your DB unit tests run in that database. You can clean it up after.

对于您提到的测试(数据库中不存在用户名和电子邮件),然后执行类似的操作(伪代码).

For the test you mentioned (username and email cannot already exist in the DB) then do something like this (psuedocode).

Create user with username that you know doesn't exist (say username-largerandomuuid)
Insert user.
Assert user was created

Insert same user(name)
Assert error is thrown.

这篇关于单元测试Dababase应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆