웹 개발

junit를 사용한 단위 테스트에서 autowired가 동작하지 않을 경우 해결 방법

노루아부지 2022. 3. 20. 20:03

[개발환경]

intellij

Spring boot

JUNIT5

 

package com.example.demo;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;

class UserServiceTest {
  @Autowired
  UserService service;

  @Test
  void insertUser() {
    service.insertUser();
    service.selectUser();
  }
}

 

위와 같이 UserService를 @Autowired한 후, 테스트를 실행하면 다음과 같은 오류가 발생합니다.

 

Cannot invoke "com.example.demo.UserService.insertUser()" because "this.service" is null
java.lang.NullPointerException: Cannot invoke "com.example.demo.UserService.insertUser()" because "this.service" is null

 

이때 다음과 같이 class 위에 @SpringBootTest 어노테이션을 추가하면 해결됩니다.

package com.example.demo;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class UserServiceTest {
  @Autowired
  UserService service;

  @Test
  void insertUser() {
    service.insertUser();
    service.selectUser();
  }
}

 

 

728x90
loading