Junit和Spring、SpringBoot測試
阿新 • • 發佈:2019-01-08
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);
}
}