drl37530 2018-07-10 19:47
浏览 16
已采纳

数据库单元测试

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!

  • 写回答

1条回答 默认 最新

  • dongxun1978 2018-07-10 19:55
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

    报告相同问题?

    悬赏问题

    • ¥30 AXI VIP验证多余打印问题
    • ¥15 利用加权最小二乘法求某品牌手机价格指标,已按照总销量计算出权重,各类型号手机价格已知,如何求得价格指标?
    • ¥15 如何自制一个硬件钱包,有兴趣的朋友一起交流
    • ¥15 (关键词-聊天软件)
    • ¥15 求大家看看这个编程的编法没有思路啊
    • ¥20 WSL打开图形化程序子窗口无法点击
    • ¥15 Jupyter Notebook 数学公式不渲染
    • ¥20 ERR_CACHE_MISS 确认重新提交表单
    • ¥20 关于vba使用HTMLfile执行js函数问题
    • ¥60 悬赏求解,通过实时现场摄像头的视频图像识别其他对家打出的麻将牌,识别麻将牌,识别牌墙位置,通过识别对家打出了什么牌