2016-09-23 76 views
-1

我有一个配置类和测试类,如下:如何测试一个具有原型范围的spring bean?

@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对象应该是不一样的,但是这个测试失败。为什么?谢谢!

+0

对于你的实验,你选择了唯一不适合Spring Bean的类型:一个字符串。另外,你为什么试图测试Spring框架代码? – kryger

回答

0

看起来像相同字符串正在被重用来从字符串池构造helloanother

如果您创建一个班级,说Person,并做相同的测试它通过测试。

1

为了提高效率,Java中的字符串汇集在一起​​。 What is the Java string pool and how is "s" different from new String("s")?

因此,即使Spring会多次调用hello()方法来尝试创建一个新对象(因为您希望原型范围),JVM仍然会返回相同的String实例。

如果你想做到以下几点,测试应该确定:

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

注意,是不好的做法是创建这样一个字符串,但对于测试的目的,这是怎么了,你可以做到这一点。