dpppic5186 2017-12-26 09:58
浏览 44

您将如何对仅用于进行数据库调用的方法进行单元测试? [关闭]

I have method something like this(golang):

func (alert *Alert) CreateAlert(db *mgo.Database) error {
    return db.C("alerts").Insert(&alert)

How should I unit test this? If I just call this method for uni test, then I will have to create test DB to which the call is made. I somehow feel that this would be part of integration test as we are making a call to DB.

If I mock the db object, then it will never test the actual implementation.

Should I test this at all? as the major goal for writing unit test if the data is inserted to DB or not, and such functionality are already tested in the library itself, in my case mgo library.

Please share your thoughts on what would be the best approach for unit testing the above scenario.

  • 写回答

1条回答 默认 最新

  • duansha7025 2017-12-26 11:03

    You would unit test it with a mock, so that the database isn't being called, but only your function is being tested.

    There are many different ways to mock a database, so I won't get into details, but a unit-test for such a small function will also be small. All you'll really be testing is that:

    1. the mock receives the expected data, in the expected format (i.e. does it receive the &alert value, passed to its Insert() method?)
    2. the mock's return value (an error) is returned to the caller of the function

    In particular, in a unit test of this function, you would not check that:

    • The SQL conforms to syntax expectations (your function doesn't control SQL, such a test would really be testing your data layer/ORM)
    • That the INSERT occurs as expected--this would be testing your database
    • That the caller of the function has appropriate database permissions (this is again testing your data layer and/or database)
    本回答被题主选为最佳回答 , 对您是否有帮助呢?



    • ¥20 powerbulider 导入excel文件,显示不完整
    • ¥30 单片机实验pc软件完全,可以私我商议
    • ¥20 #关于multisim绘图遇到的问题
    • ¥15 用keil调试程序保证结果进行led相关闪烁
    • ¥15 paddle训练自己的数据loss降不下去
    • ¥20 用matlab的pdetool解决以下三个问题
    • ¥15 单个福来轮的平衡与侧向滑动是如何做到的?
    • ¥15 嵌入式Linux固件,能直接告诉我crc32校验的区域在哪不,内核的校验我已经找到了,uboot没有
    • ¥20 h3c静态路要求有详细过程
    • ¥15 调制识别中输入为时频图,星座图,眼图等