Junit与SpringBoot的集成
需要引用maven依赖包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
写一个公共父类,把配置写在这里
package com.yanjun.springBootMybatis;
import org.junit.runner.RunWith;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
//SpringJUnit支持,由此引入Spring-Test框架支持!
@RunWith(SpringJUnit4ClassRunner.class)
//指定我们SpringBoot工程的Application启动类
@SpringApplicationConfiguration(classes = Application.class)
//由于是Web项目,Junit需要模拟ServletContext,因此我们需要给我们的测试类加上@WebAppConfiguration。
//测了,不用一下配置也可以,不知道为毛
@WebAppConfiguration
public class BaseTestCase {
}
具体的测试类,继承于父类
package com.yanjun.springBootMybatis;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import com.yanjun.springBootMybatis.service.UserService;
public class UserTest extends BaseTestCase{
@Autowired
private UserService userService;
@Test
public void testAdduser(){
boolean flag = this.userService.addUser("keven", "123456");
System.out.println(flag);
}
}
Junit和Spring
以下代码摘自网络, 并修改,未经测试。原文链接
需要引用maven依赖包
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>3.2.10.RELEASE</version>
</dependency>
写一个公共父类,把配置写在这里
package com.nicchagil.mybatis3spring3intg.junit;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"/config/application*.xml"})
public class BaseJunit {
}
具体的测试类,继承于父类
package com.nicchagil.mybatis3spring3intg.junit;
import java.util.List;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import com.yanjun.springBootMybatis.service.UserService;
public class UserServiceTest extends BaseJunit {
@Autowired
private UserService userService;
@Test
public void testAdduser(){
boolean flag = this.userService.addUser("keven", "123456");
System.out.println(flag);
}
}