junit spring注入をテストする2つの方法

1914 ワード

方法1:ロード
package spring;

import static org.junit.Assert.*;

import com.spring.model.User;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.spring.manager.UserManager;

public class UserTest {

    @Test
    public void test() {
        ApplicationContext context = new ClassPathXmlApplicationContext( "beans.xml");
        UserManager mgr = context.getBean("mgr", UserManager.class);
        com.spring.model.User u = new User("name","123");
        mgr.save(u);
    }

}


方法2:走査注入ロード
import static org.junit.Assert.*;

import javax.jws.soap.SOAPBinding.Use;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.spring.dao.entity.User;
import com.spring.service.UserService;
import com.spring.service.Impl.UserServiceImpl;


// bean   
@ContextConfiguration(locations = "classpath:beans.xml") 
@RunWith(SpringJUnit4ClassRunner.class)  
public class TestUser {

    @Autowired
    private UserService userService;
    
    @Test
    public void test() {
        
        System.out.println(userService);
//      ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
//      userService = ctx.getBean(UserServiceImpl.class);
        System.out.println(userService);
        User user = new User("wangjian","123145");
        userService.save(user);
    }

}