首页 新闻 会员 周边

java junit测试

0
悬赏园豆:5 [待解决问题]

请问 :

下面这段代码如何测试:  

@Autowired
 private UserService userService;

public String login(String userName, String pwd, String code, HttpSession session, HttpServletResponse response) {
        boolean b = userService.isLogin(userName, pwd);
        User user = userService.getUser(userName);
        if (user != null) {
            session.setAttribute("user", user);
        } else {
            return "error";
        }
        if (!(code.equalsIgnoreCase(session.getAttribute("code").toString()))) {
            return "errorcode";
        }
        if (b) {
            logger.info("========登录成功 userName:{}", userName);
            return "success";
        } else {
            logger.info("========登录失败 userName:{}", userName);
            return "error";
        }

    }

我总是注入不进去,userService总是空的。谁有比较好的办法,分享一下。谢谢。

狗霸人间的主页 狗霸人间 | 初学一级 | 园豆:4
提问于:2016-01-12 16:20
< >
分享
所有回答(3)
0
spring-test包下的类:
org.springframework.test.util.ReflectionTestUtils.setField(Object target, String name, Object value) 方法
芃朋 | 园豆:204 (菜鸟二级) | 2016-01-12 16:36
3

这里是因为没有启动Spring容器 , junit不会自动帮你启动spring容器 , 你需要在junit执行前手动创建Application , 然后在容器里拿出userService.

代码如下:

  

ApplicationContext ac = new ClassPathXmlApplicationContext("spring配置文件地址");
userService = (UserService)ac.getBean(UserService.class);
哎呦喂,我的小祖宗╰つ | 园豆:246 (菜鸟二级) | 2016-01-18 15:13

然后把 @Autowired 去掉

支持(2) 反对(0) 蜗牛大师 | 园豆:209 (菜鸟二级) | 2016-01-20 08:19
0

也可以在类上加上注解:@RunWith(SpringJUnit4ClassRunner.class)
           @ContextConfiguration({"spring配置文件地址"})

HyZxx | 园豆:202 (菜鸟二级) | 2016-02-18 14:11
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册