为什么在单元测试控制器时获取NoSuchBeanDefinitionException

时间:2011-11-19 04:12:34

标签: java spring

为什么我会遇到此异常:

  

org.springframework.beans.factory.NoSuchBeanDefinitionException:没有   类型为[org.springframework.web.servlet.HandlerAdapter]的唯一bean   定义:预期的单个bean但找到0:

   public class MyControllerIntegrationTest {
Logger logger = Logger.getLogger(MyControllerIntegrationTest.class);
@Autowired
private ApplicationContext applicationContext;

private MockHttpServletRequest request;
private MockHttpServletResponse response;
private HandlerAdapter handlerAdapter;
private TestExceptionController controller;

@Before
public void setUp() {
    request = new MockHttpServletRequest();
    response = new MockHttpServletResponse();
    handlerAdapter = applicationContext.getBean(HandlerAdapter.class);

    controller = new TestExceptionController();
}

我正在尝试运行上面的代码。我的应用程序上下文被加载并获得上述异常消息。请指导,我应该在bean定义文件中添加一些bean定义吗?

2 个答案:

答案 0 :(得分:0)

您应该使用the ApplicationContextAware interface,或者更改您的代码以直接注入HandlerAdapter(通过将@Autowired注释移动到该字段),而不是从应用程序上下文中获取它。 (除非它是原型,而不是单例,并且你真的需要在每个单元测试中使用新实例。)

答案 1 :(得分:0)

从Spring 3.0.7到Spring 3.1时,我遇到了同样的问题。

我使用这个答案解决了它:How to unit test a Spring MVC annotated controller?