数据库单元测试 [英] Database unit test

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

问题描述

我希望在编写用于测试某些数据库条目的单元测试中获得一些建议.

如果没有找到记录,则我正在测试的函数会将数据库作为种子.

  func Seed(db * gorm.DB){var data [] Datadb.Find(& data)如果len(data)== 0 {//做种子默认数据}} 

我似乎不太想去做的是len test的测试.我正在使用测试数据库,因此我可以在任何时候都对其进行核对,因此,如果我只需要在函数上强制使用一个空的数据库,那么这不是问题.

该函数本身可以正常工作,我只想确保将其覆盖.

任何建议都会很棒.

谢谢!

解决方案

这真的取决于,有很多方法可以根据您的风险水平以及您想投资的时间来减轻这些风险.>

  • 您可以编写一个单元测试,声明您无需任何数据库就可以检测用户逻辑并采取行动(例如,在空时播种,在满时忽略).
  • 如果您想通过 gorm 库测试逻辑以及程序与mysql正确对话的能力,则可以:
    • 有一个测试,您可以在数据库中没有用户的情况下调用 Seed ,在调用它之后,您的测试可以从 Users 中进行选择,并确保从中创建了预期的条目 len(users)== 0 有条件的
    • 进行一个测试,该测试将创建一个条目并调用 Seed ,然后断言基础表为空.

它会变得更加复杂.如果 Seed 选择了一个数据子集,则您的测试可能会插入2个用户,一个合格,一个不合格,并确保没有新用户成为 Seed .

I am hoping to get some advice on a unit test I am writing for to test some db entries.

The function I am testing seeds the database if no records are found.

func Seed(db *gorm.DB) {
    var data []Data
    db.Find(&data)

    if len(data) == 0 {
      // do seed default data
    }

}

What I can't quite seem to get going is the test for that if len test. I am using a test db so I can nuke it whenever so it is not an issue if I just need to force an empty DB on the function.

The function itself works and I just want to make sure I get that covered.

Any advice would be great.

Thanks!

解决方案

It really depends, there are so many ways of addressing this based on your risk level and the amount of time you want to invest to mitigate those risks.

  • You could write a unit test that asserts your able to detect and act on users logic (ie seeding when empty and ignoring when full) without any database.
  • If you would like to test the logic as well as your programs ability to speak to mysql correctly through the gorm library you could:
    • Have a test where you call Seed with no users in the DB, after calling it your test could select from Users and make sure there are the expected entries created from len(users) == 0 conditional
    • Have a test where the test creates a single entry and calls Seed, after which asserting that underlying tables are empty.

It can get more complicated. If Seed is selecting a subset of data than your test could insert 2 users, one that qualifies and one that doesnt', and make sure that no new users are Seeded.

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

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