spring使用junit进行测试时报错,出现空指针

Posted 香风智乃哈~

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了spring使用junit进行测试时报错,出现空指针相关的知识,希望对你有一定的参考价值。

控制台抛出的错误

十一月 04, 2021 12:02:58 下午 org.junit.vintage.engine.discovery.TestClassRequestResolver determineRunnerTestDescriptor
警告: Runner org.junit.internal.runners.ErrorReportingRunner (used on com.briup.test.AOPXMLTest) does not support filtering and will therefore be run completely.
null

这个错误在junit显示的是NullPointerException

//其实,这个错误的主要原因就是junit的版本不匹配
Junit4在类的开头使用的是“@RunWith”,Junit5中类的前面使用的“@ExtendWith”,所以说两个版本使用的注解是不一样的。
Junit4的“@Test”需要导入的是org.junit.Test,而Junit5的“@Test”这个注解,需要导入的是org.junit.jupiter.api.Test。
所以说,如果使用Junit4的话,就把导入改为“import org.junit.Test”。
如果使用Junit5的话,就把“@RunWith”改成“@ExtendWith”
还需要注意:使用“@RunWith”和“@ExtendWith”这两个注解时里面的参数是不同的(切记)
这样就可以解决了。

//这是我测试类里面的代码
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;

import com.briup.service.ITeacherService;


@RunWith(SpringRunner.class)
@ContextConfiguration(locations="classpath:applicationContext.xml")
public class AOPXMLTest 
	@Autowired
	private ITeacherService teacherService;

	@Test
	public void test() 
		System.out.println(teacherService);
		System.out.println(teacherService.getClass());
	
	
	@Test
	public void test_saveOrUpdate() 
		teacherService.saveOrUpdate();
	
	
	@Test
	public void test_delete() 
		teacherService.delete();
	
	
	@Test
	public void test_deleteBatch() 
		teacherService.deleteBatch();
	

以上是关于spring使用junit进行测试时报错,出现空指针的主要内容,如果未能解决你的问题,请参考以下文章

spring使用junit进行测试时报错,出现空指针

Spring Web 项目Junit测试报错问题

JUnit测试时报错

spring 环境中使用JUnit Test

使用spring-test时报错

使用 h2 进行 Spring Junit 测试 - 找不到表