ds3464 2016-08-18 22:10
浏览 43

使用测试包在golang中导入周期

I am trying to refactor some test code and in two packages I need to do the same thing (connect to a DB). I am getting an import cycle. I get why I can't do it, but am wondering what the best way around it is.

Some specifics, I have three packages: testutils, client, engine.

In engine I define an interface & implementation (both exported).

package engine
type interface QueryEngine {
  // ...
}
type struct MagicEngine {
  // ...
}

And then in the testutils package I will create a MagicEngine and try and return it.

package testutils
func CreateAndConnect() (*engine.MagicEngine, error) {
  // ....
}

Now in the test code (using a TestMain) I need to do something like

package engine
func TestMain(m *testing.M) {
  e, err := testutils.CreateAndConnect()
  // ....
  os.Exit(m.Run())
}

This is of course a cycle. I want to do this so that I can in the client package also use this testutils.CreateAndConnect() method. I don't want to repeat the code in both packages. I don't want it in the main code of the engine package, it is very specific to the tests.

I tried adding it as an exported method on the engine test class (engine/engine_test.go) and using it in the client/client_test.go. No dice. :/

I feel I have done this in other languages, but could be crazy. What is the best way to structure this code for reusability?

  • 写回答

1条回答 默认 最新

  • dragon88112 2018-03-11 06:16
    关注

    You could use black-box style testing because the components of engine are exported. Change your tests to be in package engine_test:

    package engine_test
    import "engine"
    import "testutils"
    func TestMain(m *testing.M) {
      e, err := testutils.CreateAndConnect()
      // ....
      os.Exit(m.Run())
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?