登录
首页 >  Golang >  Go问答

使用外部文件中的接口来模拟文件操作

来源:stackoverflow

时间:2024-02-20 17:54:27 347浏览 收藏

Golang小白一枚,正在不断学习积累知识,现将学习到的知识记录一下,也是将我的所得分享给大家!而今天这篇文章《使用外部文件中的接口来模拟文件操作》带大家来了解一下##content_title##,希望对大家的知识积累有所帮助,从而弥补自己的不足,助力实战开发!


问题内容

我尝试使用从另一个文件导入的接口创建文件的模拟。我尝试过“aux_files”和“imports”,但没有成功获得正确的模拟文件。我想我错过了一些东西。

所以我有一个像这样的 `mockgen/main.go` :

package main
import (
    "log"
    o "mockgen/otheri"
)

type bar struct {
    a o.foo
}

func newbar(a o.foo) *bar {
    return &bar{a}
}

func main() {
    var t = newbar(&o.functionstuct{})
    if err := t.a.ask(); err != nil {
        log.fatal(err)
    }
}

导入的接口在 `mockgen/otheri/otheri.go` 中:

package otheri

import "log"

type Foo interface {
    Ask() error
}

type FunctionStuct struct {
}

func (f *FunctionStuct) Ask() error {
    log.Println("Hello")
    return nil
}

我尝试的命令是:

mockgen -source main.go -aux_files o=otheri/otheri.go 与 main.go 执行在同一级别

但我的mockgen文件是空的......

有人有想法吗?我的目标是模拟 main.go 中包含的接口 o.foo ,而不改变我的架构

我需要模拟它以通过单元测试来测试它。 架构是这样的,因为我遵循干净的架构。 谢谢大家


正确答案


您只能为接口生成模拟。因此,在您的示例中,您应该为文件 mockgen/otheri/otheri.go 运行模拟生成,因为目标接口出现在何处。

但正如 elias van ootegem 指出的那样,与符合它的结构建立接口是一种不好的做法。您应该将接口和实现分开。 所以,它应该是这样的:

文件 /bar/bar.go

package bar

import (
    "log"
)

type foo interface {
    ask() error
}

type bar struct {
    foo foo
}

func newbar(a foo) *bar {
    return &bar{a}
}

func (b *bar) ask() {
    if err := b.foo.ask(); err != nil {
        log.fatal(err)
    }
}

文件 otheri/otheri.go

package otheri

import "log"

type functionstruct struct {
}

func (f *functionstruct) ask() error {
    log.println("hello")
    return nil
}

文件 main.go

package main

import (
    "bar"
    "otheri"
)

func main() {
    fs := &otheri.functionstruct{}
    b := bar.newbar(fs)
    b.ask()
}

并生成一个模拟 mockgen -source=bar/bar.go -destination=bar/mock/foo_mock.go foo

此外,请遵循 effective go 使用 functionstruct 的最佳方式中描述的规则 - 隐藏包中的类型:

因此,最终的解决方案是将接口移动到单独的包中:

文件 /foo/foo.go

package foo

type foo interface {
    ask() error
}

文件 /bar/bar.go

package bar

import (
    "log"
    "foo"
)

type bar struct {
    foo foo.foo
}

func newbar(a foo.foo) *bar {
    return &bar{a}
}

func (b *bar) ask() {
    if err := b.foo.ask(); err != nil {
        log.fatal(err)
    }
}

文件 otheri/otheri.go

package otheri

import ( 
   "log"
   "foo"
)

func new() foo.foo {
    return &functionstruct{}
}

type functionstruct struct {
}

func (f *functionstruct) ask() error {
    log.println("hello")
    return nil
}

文件 main.go

package main

import (
    "bar"
    "otheri"
)

func main() {
    b := bar.NewBar(otheri.New())
    b.Ask()
}

和模拟生成:mockgen -source=foo/foo.go -destination=foo/mock/foo_mock.go foo

理论要掌握,实操不能落!以上关于《使用外部文件中的接口来模拟文件操作》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>