-1

I have a configuration class and a test class as below:

@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);
    }
}

According to the definition of prototype scope, the hello and another object should be not same, but this test failed. Why? Thanks!

walsh
  • 3,041
  • 2
  • 16
  • 31
  • For your experiment you picked about the only type that's not suitable for a Spring Bean: a String. Also, why are you trying to test Spring Framework code? – kryger Sep 23 '16 at 12:46

2 Answers2

1

Strings in Java are pooled for effeciency. You can read more about it here: What is the Java string pool and how is "s" different from new String("s")?

So, even though Spring will call your hello() method multiple times to try to create a new object (since you want prototype scope), the JVM will return the same String instance anyway.

If you would do the following, the test should be ok:

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

Note that is is bad practise to create a String like this, but for the purpose of your test, this is how you can do it.

Community
  • 1
  • 1
Wim Deblauwe
  • 25,113
  • 20
  • 133
  • 211
0

Seems like same String is being reused to construct both hello and another from String pool.

If you create a class, say Person, and do the same test it is passing the test.

K. Siva Prasad Reddy
  • 11,786
  • 12
  • 68
  • 95