草庐IT

go - 当用 * 实例化 var 时,单例测试不起作用

coder 2023-07-02 原文

我正在遵循本书 (https://github.com/PacktPublishing/Go-Design-Patterns/blob/master/Chapter02/main.go) 中描述的单例设计模式,并且我在文件“singleton2.go”中有以下代码:

package singleton2

type Singleton interface {
  AddOne() int
}

type singleton struct {
  count int
}

//var instance = &singleton{}
var instance *singleton

func GetInstance() *singleton {
  if instance == nil {
    return new(singleton)
  }
  return instance
}

func (s *singleton) AddOne() int {
  s.count++
  return s.count
}

然后我有这个测试文件(singleton2_test.go):

package singleton2

import "testing"

func TestGetInstance(t *testing.T) {
  counter1 := GetInstance()
  if counter1 == nil {
    t.Fatal("expected pointer to Singleton after calling GetInstance(), not nil")
  }

  expectedCounter := counter1

  currentCount := counter1.AddOne()
  if currentCount != 1 {
    t.Errorf("After calling for the first time to count, the counter must be 1 but it is %d", currentCount)
  }

  counter2 := GetInstance()
  if counter2 != expectedCounter {
    t.Errorf("Expected same instance in counter2 but it got a different instance.")
    t.Logf("Got %v, want %v", counter2, expectedCounter)
  }

  currentCount = counter2.AddOne()
  if currentCount != 2 {
    t.Errorf("After calling AddOne() using second counter, the count must be 2, but it was %d", currentCount)
  }

}

问题是测试总是失败:

--- FAIL: TestGetInstance (0.00s)
    singleton2_test.go:20: Expected same instance in counter2 but it got a different instance.
    singleton2_test.go:21: Got &{0}, want &{1}
    singleton2_test.go:26: After calling AddOne() using second counter, the count must be 2, but it was 1
FAIL
exit status 1
FAIL    github.com/d3c3/design_patterns/singleton/singleton2    0.029s

有趣的是,如果我将此行 var instance *singleton 更改为此行 var instance = &singleton{} 测试通过!?这是为什么? IMO,它也应该与“var instance *singleton”一起使用

谁能解释这种行为差异?

最佳答案

遵循代码的逻辑,很明显问题出在哪里。

当您声明但不初始化单例 (var instance *singleton) 时,instancenil。调用 GetInstance 会将 instance == nil 评估为 true 并在每次调用时返回一个新的 *singleton。这就是为什么 counter2 永远不会等于 expectedCounter - 每次调用 GetInstance 都会返回一个新的计数器实例。

当您初始化单例实例 (var instance = &singleton{}) 时,调用 GetInstance 将返回该单例实例,因为它不是nil.

我想您可能希望将 GetInstance 修改为如下内容:

func GetInstance() *singleton {
    if instance == nil {
        instance = new(singleton)
    }
    return instance
}

编辑

虽然你没有提到你需要这个单例是线程安全的,用户colminator正确地指出,以这种方式实例化一个单例可能会导致多个 go-routines 实例化它们自己的单例实例,从而破坏了拥有一个单例的目的。鉴于 Golang 中的并发性如此之高,了解更多可能会有所帮助! Check out the link he posted here .

关于go - 当用 * 实例化 var 时,单例测试不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56534491/

有关go - 当用 * 实例化 var 时,单例测试不起作用的更多相关文章

  1. ruby-on-rails - 使用 Ruby on Rails 进行自动化测试 - 最佳实践 - 2

    很好奇,就使用ruby​​onrails自动化单元测试而言,你们正在做什么?您是否创建了一个脚本来在cron中运行rake作业并将结果邮寄给您?git中的预提交Hook?只是手动调用?我完全理解测试,但想知道在错误发生之前捕获错误的最佳实践是什么。让我们理所当然地认为测试本身是完美无缺的,并且可以正常工作。下一步是什么以确保他们在正确的时间将可能有害的结果传达给您? 最佳答案 不确定您到底想听什么,但是有几个级别的自动代码库控制:在处理某项功能时,您可以使用类似autotest的内容获得关于哪些有效,哪些无效的即时反馈。要确保您的提

  2. ruby - 使用 C 扩展开发 ruby​​gem 时,如何使用 Rspec 在本地进行测试? - 2

    我正在编写一个包含C扩展的gem。通常当我写一个gem时,我会遵循TDD的过程,我会写一个失败的规范,然后处理代码直到它通过,等等......在“ext/mygem/mygem.c”中我的C扩展和在gemspec的“扩展”中配置的有效extconf.rb,如何运行我的规范并仍然加载我的C扩展?当我更改C代码时,我需要采取哪些步骤来重新编译代码?这可能是个愚蠢的问题,但是从我的gem的开发源代码树中输入“bundleinstall”不会构建任何native扩展。当我手动运行rubyext/mygem/extconf.rb时,我确实得到了一个Makefile(在整个项目的根目录中),然后当

  3. ruby - Ruby 的 Hash 在比较键时使用哪种相等性测试? - 2

    我有一个围绕一些对象的包装类,我想将这些对象用作散列中的键。包装对象和解包装对象应映射到相同的键。一个简单的例子是这样的:classAattr_reader:xdefinitialize(inner)@inner=innerenddefx;@inner.x;enddef==(other)@inner.x==other.xendenda=A.new(o)#oisjustanyobjectthatallowso.xb=A.new(o)h={a=>5}ph[a]#5ph[b]#nil,shouldbe5ph[o]#nil,shouldbe5我试过==、===、eq?并散列所有无济于事。

  4. ruby-on-rails - 如何使用 instance_variable_set 正确设置实例变量? - 2

    我正在查看instance_variable_set的文档并看到给出的示例代码是这样做的:obj.instance_variable_set(:@instnc_var,"valuefortheinstancevariable")然后允许您在类的任何实例方法中以@instnc_var的形式访问该变量。我想知道为什么在@instnc_var之前需要一个冒号:。冒号有什么作用? 最佳答案 我的第一直觉是告诉你不要使用instance_variable_set除非你真的知道你用它做什么。它本质上是一种元编程工具或绕过实例变量可见性的黑客攻击

  5. ruby 正则表达式 - 如何替换字符串中匹配项的第 n 个实例 - 2

    在我的应用程序中,我需要能够找到所有数字子字符串,然后扫描每个子字符串,找到第一个匹配范围(例如5到15之间)的子字符串,并将该实例替换为另一个字符串“X”。我的测试字符串s="1foo100bar10gee1"我的初始模式是1个或多个数字的任何字符串,例如,re=Regexp.new(/\d+/)matches=s.scan(re)给出["1","100","10","1"]如果我想用“X”替换第N个匹配项,并且只替换第N个匹配项,我该怎么做?例如,如果我想替换第三个匹配项“10”(匹配项[2]),我不能只说s[matches[2]]="X"因为它做了两次替换“1fooX0barXg

  6. ruby - RSpec - 使用测试替身作为 block 参数 - 2

    我有一些Ruby代码,如下所示:Something.createdo|x|x.foo=barend我想编写一个测试,它使用double代替block参数x,这样我就可以调用:x_double.should_receive(:foo).with("whatever").这可能吗? 最佳答案 specify'something'dox=doublex.should_receive(:foo=).with("whatever")Something.should_receive(:create).and_yield(x)#callthere

  7. ruby-on-rails - 如果 Object::try 被发送到一个 nil 对象,为什么它会起作用? - 2

    如果您尝试在Ruby中的nil对象上调用方法,则会出现NoMethodError异常并显示消息:"undefinedmethod‘...’fornil:NilClass"然而,有一个tryRails中的方法,如果它被发送到一个nil对象,它只返回nil:require'rubygems'require'active_support/all'nil.try(:nonexisting_method)#noNoMethodErrorexceptionanymore那么try如何在内部工作以防止该异常? 最佳答案 像Ruby中的所有其他对象

  8. ruby - Sinatra:运行 rspec 测试时记录噪音 - 2

    Sinatra新手;我正在运行一些rspec测试,但在日志中收到了一堆不需要的噪音。如何消除日志中过多的噪音?我仔细检查了环境是否设置为:test,这意味着记录器级别应设置为WARN而不是DEBUG。spec_helper:require"./app"require"sinatra"require"rspec"require"rack/test"require"database_cleaner"require"factory_girl"set:environment,:testFactoryGirl.definition_file_paths=%w{./factories./test/

  9. ruby-on-rails - 迷你测试错误 : "NameError: uninitialized constant" - 2

    我遵循MichaelHartl的“RubyonRails教程:学习Web开发”,并创建了检查用户名和电子邮件长度有效性的测试(名称最多50个字符,电子邮件最多255个字符)。test/helpers/application_helper_test.rb的内容是:require'test_helper'classApplicationHelperTest在运行bundleexecraketest时,所有测试都通过了,但我看到以下消息在最后被标记为错误:ERROR["test_full_title_helper",ApplicationHelperTest,1.820016791]test

  10. ruby - 即使失败也继续进行多主机测试 - 2

    我已经构建了一些serverspec代码来在多个主机上运行一组测试。问题是当任何测试失败时,测试会在当前主机停止。即使测试失败,我也希望它继续在所有主机上运行。Rakefile:namespace:specdotask:all=>hosts.map{|h|'spec:'+h.split('.')[0]}hosts.eachdo|host|begindesc"Runserverspecto#{host}"RSpec::Core::RakeTask.new(host)do|t|ENV['TARGET_HOST']=hostt.pattern="spec/cfengine3/*_spec.r

随机推荐