Spring Boot整合Junit

一、main方法启动spring
    new ClasspathXmlApplicationContext("applicationContext.xml");
二、spring整合junit
    //@RunWith(SpringJUnit4ClassRunner.class)
    @RunWith(SpringRunner.class)
    @ContextConfiguration("classpath:applicationContext.xml")
三、springboot整合junit
    @RunWith(SpringJUnit4ClassRunner.class)
    @SpringBootTest(classes={SpringbootJunit.class})

Junit启动器


		
			org.springframework.boot
			spring-boot-starter-test
		

 

编写业务代码

dao

@Repository
public class UserDaoImpl {

	public void saveUser(){
		System.out.println("insert into users.....");
	}
}

service

@Service
public class UserServiceImpl {

	@Autowired
	private UserDaoImpl userDaoImpl;
	
	public void addUser(){
		this.userDaoImpl.saveUser();
	}
}

app

@SpringBootApplication
public class App {

	public static void main(String[] args) {
		SpringApplication.run(App.class, args);
	}
}

整合Junit

/**
 *  main方法:
 *		ApplicationContext ac=new 
 *       			ClassPathXmlApplicationContext("classpath:applicationContext.xml");
 *  junit与spring整合:
 *      @RunWith(SpringJUnit4ClassRunner.class):让junit与spring环境进行整合
 *   	@Contextconfiguartion("classpath:applicationContext.xml")  
 */
@RunWith(SpringJUnit4ClassRunner.class) 
@SpringBootTest(classes={App.class})
public class UserServiceTest {

	@Autowired
	private UserServiceImpl userServiceImpl;
	
	@Test
	public void testAddUser(){
		this.userServiceImpl.addUser();
	}
}

你可能感兴趣的:(spring,boot,junit,后端)