开发者社区 问答 正文

spring使用JUnit时autowired报错

试了好多办法还是不行,不知道哪里配错了。麻烦大神帮看一下异常信息:
screenshot
UserTest.java
screenshot
UserServiceImpl.java(这个是service的实现)
screenshot
applicationContext.xml(我感觉我可能是这里不对)
screenshot
springmvc-servlet.xml(我在controller里autowired是没有问题的)
screenshot

展开
收起
蛮大人123 2016-02-26 10:38:43 3270 分享 版权
1 条回答
写回答
取消 提交回答
  • 我说我不帅他们就打我,还说我虚伪

    junit测试这个方法的时候你要自己去获取userService这个服务,junit单元测试其实是一个独立的单元测试,它跟Spring的容器是没有关系的。示例代码如下:我的spring的配置文件在WebContent/WEB-INF/config下。

    public class TestUserService extends TestCase {
    
        private CurUserService userService;
    
        @Override
        protected void setUp() throws Exception {
            ApplicationContext ac = new FileSystemXmlApplicationContext("WebContent/WEB-INF/config/applicationContext.xml");
            userService = (CurUserService)ac.getBean("cuserService");
            System.out.println(userService==null);
        }
    
        public void testGetValue(){
            Assert.assertEquals(userService.getValue(), 10);
        }
    }
    2019-07-17 18:47:59
    赞同 展开评论