Spring单元测试类ApplicationTests错误


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());
	}
	
}

Spring单元测试类ApplicationTests错误_第1张图片




你可能感兴趣的:(SpringBoot,springboot测试,spring错误)