Spring單元測試類ApplicationTests錯誤
阿新 • • 發佈:2019-01-22
1)正確寫法
package com.boot.demo02restful; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.boot.restful.Application; import com.boot.restful.service.UserService; @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes=Application.class) public class ApplicationTests { @Autowired @Qualifier(value="myUserService") private UserService userSerivce; @Before public void setUp() { // 準備,清空user表 userSerivce.deleteAllUsers(); } @Test public void test() throws Exception { // 插入5個使用者 userSerivce.create("a", 1); userSerivce.create("b", 2); userSerivce.create("c", 3); userSerivce.create("d", 4); userSerivce.create("e", 5); // 查資料庫,應該有5個使用者 Assert.assertEquals(5, userSerivce.getAllUsers().intValue()); // 刪除兩個使用者 userSerivce.deleteByName("a"); userSerivce.deleteByName("e"); // 查資料庫,應該有5個使用者 Assert.assertEquals(3, userSerivce.getAllUsers().intValue()); } }
2)異常寫法
package com.boot.demo02restful; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.boot.restful.Application; import com.boot.restful.service.UserService; @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest public class ApplicationTests { @Autowired @Qualifier(value="myUserService") private UserService userSerivce; @Before public void setUp() { // 準備,清空user表 userSerivce.deleteAllUsers(); } @Test public void test() throws Exception { // 插入5個使用者 userSerivce.create("a", 1); userSerivce.create("b", 2); userSerivce.create("c", 3); userSerivce.create("d", 4); userSerivce.create("e", 5); // 查資料庫,應該有5個使用者 Assert.assertEquals(5, userSerivce.getAllUsers().intValue()); // 刪除兩個使用者 userSerivce.deleteByName("a"); userSerivce.deleteByName("e"); // 查資料庫,應該有5個使用者 Assert.assertEquals(3, userSerivce.getAllUsers().intValue()); } }