在不使用接口的情况下,如何对外部库进行模拟函数的翻译。

huangapple go评论71阅读模式
英文:

Go mock function from extenal lib without interface

问题

我已经为我们的程序使用了以下日志记录器lib
我们已经创建了单元测试,并且我们需要为版本0.4.0提供模拟。
https://github.com/go-logr/logr/blob/v0.4.0/logr.go#L148

这是我们如何模拟这些函数的方式,它们按预期工作。

type testLog struct {
    msg   string
    key   string
    value string
}

func (log *testLog) Enabled() bool {
    return true
}

func (log *testLog) Info(msg string, keysAndValues ...interface{}) {
    log.msg = msg
    log.key = keysAndValues[0].(string)
    log.value = keysAndValues[1].(string)
}

func (log *testLog) Error(err error, msg string, keysAndValues ...interface{}) {
}

func (log *testLog) V(level int) logr.Logger {
    return &testLog{}
}

func (log *testLog) WithValues(keysAndValues ...interface{}) logr.Logger {
    return &testLog{}
}

func (log *testLog) WithName(name string) logr.Logger {
    return &testLog{}
}

现在我们需要升级到版本1.2.0,实现已经改变,没有接口
我的问题是,我应该如何使用新版本进行模拟记录器?

请参阅以下链接中的相关函数:
https://github.com/go-logr/logr/blob/v1.2.2/logr.go#L230

英文:

I’ve used the following logger lib for our program.
We have create unit tests and we need to provide mock for version 0.4.0
https://github.com/go-logr/logr/blob/v0.4.0/logr.go#L148

This is how we mocked the functions which works as expected

type testLog struct {
	msg   string
	key   string
	value string
}

func (log *testLog) Enabled() bool {
	return true
}

func (log *testLog) Info(msg string, keysAndValues ...interface{}) {
	log.msg = msg
	log.key = keysAndValues[0].(string)
	log.value = keysAndValues[1].(string)
}

func (log *testLog) Error(err error, msg string, keysAndValues ...interface{}) {
}

func (log *testLog) V(level int) logr.Logger {
	return &testLog{}
}

func (log *testLog) WithValues(keysAndValues ...interface{}) logr.Logger {
	return &testLog{}
}

func (log *testLog) WithName(name string) logr.Logger {
	return &testLog{}
}

Now we need to upgrade to version 1.2.0
And the implementation is changed, there is no interface.
My question is how should I mock the logger with the new version ?

See this link with the followed functions
https://github.com/go-logr/logr/blob/v1.2.2/logr.go#L230

答案1

得分: 1

我的问题是如何使用新版本来模拟日志记录器?

你不能这样做。需要采用一种非基于模拟的测试策略。

英文:

> My question is how should I mock the logger with the new version ?

You cannot. Come up with a non mock-based testing strategy.

huangapple
  • 本文由 发表于 2022年2月14日 04:59:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/71104803.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定