簡體   English   中英

如何測試具有原型范圍的 spring bean?

[英]How to test a spring bean with prototype scope?

我有一個配置類和一個測試類,如下所示:

@Configuration
public class SimpleConfiguration {
    @Bean
    @Scope(scopeName = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    public String hello() {
        return "hello";
    }
}

@RunWith(SpringRunner.class)
@ContextConfiguration(classes = SimpleConfiguration.class)
public class SimpleTest {
    @Autowired
    private String hello;

    @Autowired
    private String another;

    @Test
    public void should_not_same() {
        Assert.assertNotSame(hello, another);
    }
}

根據prototype scope的定義, helloanother對象應該不一樣,但是這次測試失敗了。 為什么? 謝謝!

Java 中的字符串被池化以提高效率。 您可以在此處閱讀更多相關信息: 什么是 Java 字符串池以及“s”與 new String("s") 有何不同?

所以,即使 Spring 會多次調用你的hello()方法來嘗試創建一個新對象(因為你想要原型范圍),JVM 無論如何都會返回相同的 String 實例。

如果您會執行以下操作,則測試應該沒問題:

public String hello() {
    return new String("hello");
}

請注意,創建這樣的 String 是不好的做法,但為了您的測試目的,您可以這樣做。

似乎正在重用相同的 String 來構造hello和 String 池中的another

如果你創建一個類,比如Person ,並做同樣的測試,它就會通過測試。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM