JUnit4使用Spring annotation注解

    编写的一个web程序,想通过一个Junit来对其增加用户,这样保持它的相对独立性。

    之前使用的是ApplicationContext的方式,来getBean()。之后,配置完spring和struts2,把applicationContext.xml的由src转到WebRoot下的Web-INF中,从而导致ApplicationContext的getbean找不到配置文件,出现空指针的错误。果断想到用spring的注入。但是,直接的注入还是空指针的错误,网上查的说是JUnit是一个框架,Spring是另一个框架,两者之间是独立的,没有上下文关系,若JUnit4中想用Spring的注入的话,还是需要一些配置的:

1、增加org.springframework.test-3.0.1.RELEASE-A.jar(不一定是此版本,我的是myeclipse8.6自带

2、import org.springframework.test.context.ContextConfiguration;

     import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

3、@RunWith(SpringJUnit4ClassRunner.class)

    @ContextConfiguration(locations={"file:WebRoot/WEB-INF/applicationContext.xml(你的配置文件位置)"})

 

  在此之后,就可以像普通的action来注入你的service了

我的JUnit:

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.idealing.model.LUserManager;
import com.idealing.service.UserService;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"file:WebRoot/WEB-INF/applicationContext.xml"})

public class userServiceTest {
    
   
    @Before
    public void setUp() throws Exception {
        System.out.println("testBegin...");
    }

    @After
    public void tearDown() throws Exception {
        System.out.println("testSuccess!");
    }
    private UserService userService;
     @Resource(name="userService")
        public void setUserService(UserService userService) {
            this.userService = userService;
        }

        public UserService getUserService() {
            return userService;
        }
    @Test
    public void testAdd() {
         String userName ="XXX";
         String userPassword = "***";
         String userType ="0";
         if(this.userService.addUser(userName, userPassword, userType))    
            ;
         else
             System.out.println("The userName is exist!!");
    }

    @Test
    public void testFindByUserName() {
            List<LUserManager> users =new ArrayList<LUserManager>();
            this.userService.findAll(users);
            if(users == null)
                System.out.println("There is no user!");
            else
            {
                for(LUserManager user:users)
                {
                 System.out.println("userId是:"+user.getUserId());
                 System.out.println("userName是:"+user.getUserName());
                 System.out.println("user所属类型是:"+user.getUserType().toString());    
                 System.out.println("user密码是:"+user.getUserPassword().toString());
                }
            }
    }
 
}

 

  

 

 

posted @ 2013-06-13 21:25  idealing  阅读(2357)  评论(0编辑  收藏  举报