Spring 整合 Junit 一直报 java.lang.NullPointerException

文章目录

  • 1. 异常信息
  • 2. 测试代码
  • 3. `build.gradle`
  • 4. 问题分析
  • 5. 解决方案

1. 异常信息

java.lang.NullPointerException
	at com.wen.basic.app.SpringJunitTest.testSpringJunit(SpringJunitTest.java:30)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at 
	...

2. 测试代码

import com.wen.basic.config.SpringConfiguration;
import com.wen.basic.service.UserAnnotationService;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import javax.annotation.Resource;

/**
 * 测试代码
 *
 * @author wenqing_liu
 * @date 2022/1/10
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {SpringConfiguration.class})
public class SpringJunitTest {

    @Resource
    public UserAnnotationService userAnnotationService;

    @Test
    void testSpringJunit() {
        userAnnotationService.save();
    }
}

3. build.gradle

dependencies {
    testImplementation 'junit:junit:4.11'
    testImplementation 'org.junit.jupiter:junit-jupiter-api:5.7.2'
    testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.7.2'
    implementation 'mysql:mysql-connector-java:8.0.27'
    implementation 'org.mybatis:mybatis:3.5.9'
    implementation 'org.springframework:spring-context:5.3.14'
    testImplementation 'org.springframework:spring-test:5.3.14'
    implementation 'com.alibaba:druid:1.2.8'
    compileOnly 'org.projectlombok:lombok:1.18.20'
}

4. 问题分析

  • 测试代码是没有问题的
  • 问题的关键是:Junit4 和Junit5 混合使用了。
  • @RunWith() 注解是Junit4的使用方式
  • Spring 整合Junit5 的其中一种方式是:@SpringJUnitConfig(classes = SpringConfiguration.class)

5. 解决方案

  • build.gradle中删除junit4
  • 测试类中使用Junit5方式
    package com.wen.basic.app;
    
    import com.wen.basic.config.SpringConfiguration;
    import com.wen.basic.service.UserAnnotationService;
    import org.junit.jupiter.api.Test;
    import org.springframework.test.context.ContextConfiguration;
    import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
    import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    
    import javax.annotation.Resource;
    
    /**
     * TODO
     *
     * @author wenqing_liu
     * @date 2022/1/10
     */
    @SpringJUnitConfig(classes = SpringConfiguration.class)
    public class SpringJunitTest {
    
        @Resource
        public UserAnnotationService userAnnotationService;
    
        @Test
        void testSpringJunit() {
            userAnnotationService.save();
        }
    }
    

你可能感兴趣的:(Java基础学习笔记,java,spring,gradle,junit)