欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

junit测试spring注入的两种方法

程序员文章站 2024-02-09 18:18:46
...

方法一:
加载

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);
    }

}

方法二:
扫描注入加载

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);
    }

}