Spring单元测试类ApplicationTests错误

来源:互联网 发布:网络维护费用清单 编辑:程序博客网 时间:2024/06/05 14:20


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;@Beforepublic void setUp() {// 准备,清空user表userSerivce.deleteAllUsers();}@Testpublic 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)@SpringBootTestpublic class ApplicationTests {@Autowired@Qualifier(value="myUserService")private UserService userSerivce;@Beforepublic void setUp() {// 准备,清空user表userSerivce.deleteAllUsers();}@Testpublic 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());}}





原创粉丝点击