如何在测试时在控制器内自动装配Spring bean?

时间:2013-11-19 15:08:19

标签: java spring spring-mvc junit

我有一个Spring测试:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:my-context.xml")
    public class MyTest {
        @Test
        public void testname() throws Exception {
           System.out.println(myController.toString());
        }

        @Autowired
        private MyController myController;
    }

当myController与MyTest在同一个类中定义时,这个工作正常但是如果我将MyController移动到另一个类它没有自动装配,因为下面的运行返回null,所以myController似乎没有正确自动装配:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:my-context.xml")
        public class MyTest {
            @Test
            public void testname() throws Exception {
               System.out.println(new TestClass().toString());
            }

        }

    @Controller
    public class TestClass {
            @Autowired
            private MyController myController;

            public String toString(){
              return myController.toString();       
            }
    }

自动装配是否只发生在运行测试的类中?如何在测试类实例化的所有类上启用自动装配?

更新:

感谢smajlo&的回答Philipp Sander我能够使用此代码修复此问题以访问此bean而不是显式创建bean。这已由Spring配置,因此我从上下文中访问它:

ApplicationContext ctx = new ClassPathXmlApplicationContext("my-context.xml");  
TestClass myBean = (TestClass) ctx.getBean("testClass");  

当明确创建bean时,Spring不会自动装配它。

2 个答案:

答案 0 :(得分:1)

new TestClass().toString()

如果通过手动调用构造函数创建对象,则obejct不受Spring控制,因此字段不会自动装配。

编辑:

也许您想要创建特定的测试上下文并在测试类上加载它们。因为现在我猜你的测试方法有点不对。 为什么需要从测试类访问另一个测试类?这不再是单元测试了:))

无论您要添加什么注释,您的TestClass都将永远不会自动装配,因为您创建了新实例。 试试这个:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:my-context.xml")
    public class MyTest {
    @Autowired
    private TestClass testClass;
        @Test
        public void testname() throws Exception {
           System.out.println(testClass.toString());
        }

    }

@Controller
public class TestClass {
        @Autowired
        private MyController myController;

        public String toString(){
          return myController.toString();       
        }
}

答案 1 :(得分:0)

Sotirios Delimanolis已经说过:

MyTestClass需要由Spring管理以获得自动装配。要做到这一点,只需在@Component到MyTestClass并自动装配它