0

I know there are many posts related to JUnit5 env setting, but I am not sure why I still get the null injection. My unittest is for bellow to be referred to.

import com.example.demo.service.processing.Task;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;                 // the right one is used.
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;

import static org.junit.jupiter.api.Assertions.*;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit.jupiter.SpringExtension;

@ExtendWith(SpringExtension.class)  //in JUnit5, these 2 are required.
@SpringBootTest
public class ProcessorUT {
    // some works, settings,
    @Autowired
    private static TransactionServiceImpl service;
    @BeforeAll
    public static void initBeforeAll(){
        //here the service is null
    }
    @BeforeEach
    public void initBeforeEach() {
        //service is null
    }
    @Test
    public void test_initProcessor(){
        //service is null
    }
}

the maven dependency is from spring initializer,

  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.7.4</version>
    <relativePath/> <!-- lookup parent from repository -->
  </parent>

I also tried dependency bellow, but everything is the same. I think I am in the JUnit5 env based on spring-boot-starter-test with JUnit 5 . So what may be the issue? Any info is appreciated.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <version>2.7.4</version>
    <scope>test</scope>
</dependency>
Yu Fang
  • 520
  • 5
  • 17
  • 4
    It's `static`...thus probably always null! https://stackoverflow.com/q/1018797/592355 – xerx593 Oct 12 '22 at 10:56
  • 1
    Just "try to" make the "beforeAll" (+variable) non-static!;) https://stackoverflow.com/q/55719014/592355 – xerx593 Oct 12 '22 at 10:58
  • 1
    Also, it's not really a unit test if you need to autowire something. Unit tests should use the constructor of the class under test, mocking dependencies as needed. If you do autowire something it becomes an integration test (testing multiple units) – Deltharis Oct 12 '22 at 11:00

0 Answers0