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)
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line