springboot,springmvc使用Junit單元測試
常見開發過程中在spring相關的框架裏面,我們聲明類的時候都是使用spring的依賴注入,新接觸的童鞋不可能有這個疑惑,當我要鏈接數據庫或使用方法進行測試的時候,在不啓動的情況下,是無法注入jdbc,mapper,service的。其實junit單元測試給我們很好的解決了這個問題。對於對這塊不瞭解的。下面簡單說明一下。
1、首先pom.xml引入單元測試Junit包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
2、爲了我們每次使用單元測試的時候代價小一點,我們先構造一個單元測試的java類,以後要進行測試的類繼承他即可。
import org.junit.After;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import com.sunreal.run.Startup;
@RunWith(SpringRunner.class)
@SpringBootTest(classes=Startup.class)//這裏是springboot啓動類
@WebAppConfiguration
public class JUnitDaoBase extends AbstractTransactionalJUnit4SpringContextTests {
@Before
public void init() {
System.out.println("開始測試-----------------");
}
@After
public void after() {
System.out.println("測試結束-----------------");
}
}
注意@springboottest註解爲啓動的calss類,類中代碼不用修改,直接複製貼進去即可。
3、單元測試
import java.util.List;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import com.sunreal.unify.accidentandidentify.dao.Ldc1Mapper;
import com.sunreal.unify.accidentandidentify.dto.Ldc1Dto;
import com.sunreal.unify.accidentandidentify.po.Ldc1;
import com.sunreal.unify.accidentandidentify.po.Ldc1Key;
public class DoTest extends JUnitDaoBase{
@Autowired
Ldc1Mapper Ldc1Mapper;
//@Ignore("not ready yet")
@Test
public void test() {
Ldc1Key key = new Ldc1Key();
key.setAab301("133101");
key.setBlc002(2020061101l);
Ldc1 ldc1 = Ldc1Mapper.selectByPrimaryKey(key);
System.out.println(ldc1.getAlc020());
List<Ldc1Dto> list = Ldc1Mapper.searchLdc1ByAab001AndAac002("130000302724", "310101199008019992", "41");
System.out.println(list.get(0).getAlc020());
}
}
這裏例如autowired等需要注入的類就不會空指針了,注意運行單元測試,拿eclipse舉例,右鍵->run as ->junittest.。。。。你想debug也是可以的
================================================================
以上是springboot下的操作方式,當然我們常見web項目還有springmvc,下面把springmvc也說一下,因爲大體實現方式都一樣,也都是簡歷一個公共類,單元測試進行繼承,這裏簡單說一下代碼
import org.junit.BeforeClass;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:applicationContext.xml"})
public class BasicTest {
@BeforeClass
public static void setUp() throws Exception {
System.out.println("啓動Spring測試!");
}
}
就不詳細展示調用方式了,道理基本上一樣的。