最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

spring boot - What's wrong that always returns null for the repository and the test fails? - Stack Overflow

programmeradmin0浏览0评论

my test method always fails, and I always get the error below:

java.lang.NullPointerException: Cannot invoke "com.priserp.springapipeta.repository.EmpresaRepository.findAll()" because "this.empresaRepository" is null

at com.priserp.springapipeta.service.EmpresaService.getAllEmpresas(EmpresaService.java:53) at com.priserp.springapipeta.unit.service.EmpresaServiceTest.should_Return_All_Empresas(EmpresaServiceTest.java:66) at java.base/java.lang.reflect.Method.invoke(Method.java:580) at java.base/java.util.ArrayList.forEach(ArrayList.java:1596) at java.base/java.util.ArrayList.forEach(ArrayList.java:1596)

my service:

@Service
public class EmpresaService {

    private final EmpresaRepository empresaRepository;

    public List<Empresa> getAllEmpresas() {
        return empresaRepository.findAll();
    }

}

@Repository
public interface EmpresaRepository extends JpaRepository<Empresa, Long> {
    Optional<Empresa> findByRazaoSocial(String name);
    Optional<Empresa> findByCnpj(String cnpj);
}

my test class, I want to check if the method returns a list but this list is always empty or index out of bounds

@RunWith(MockitoJUnitRunner.class)
@SpringBootTest(classes = PetaApiApplication.class)
class EmpresaServiceTest {
    @Mock
    EmpresaRepository empresaRepository;

    @InjectMocks
    EmpresaService empresaService = new EmpresaService(empresaRepository);

    private final List<Empresa> empresas = new ArrayList<>();

    @Test
    public void should_Return_All_Empresas() {
        Empresa empresa1 = new Empresa(1L, "EMPRESA 1", "12345678");
        Empresa empresa2 = new Empresa(2L, "EMPRESA 2", "456");
        empresas.add(empresa1);
        empresas.add(empresa2);    
        when(empresaRepository.findAll()).thenReturn(empresas);

        List<Empresa> foundEmpresas = this.empresaService.getAllEmpresas();

        assertNotEquals(null, foundEmpresas);

        assertEquals("EMPRESA 1", foundEmpresas.get(0).getRazaoSocial());

        System.out.println(foundEmpresas.size());
        System.out.println(empresas.size());

    }

}

my test method always fails, and I always get the error below:

java.lang.NullPointerException: Cannot invoke "com.priserp.springapipeta.repository.EmpresaRepository.findAll()" because "this.empresaRepository" is null

at com.priserp.springapipeta.service.EmpresaService.getAllEmpresas(EmpresaService.java:53) at com.priserp.springapipeta.unit.service.EmpresaServiceTest.should_Return_All_Empresas(EmpresaServiceTest.java:66) at java.base/java.lang.reflect.Method.invoke(Method.java:580) at java.base/java.util.ArrayList.forEach(ArrayList.java:1596) at java.base/java.util.ArrayList.forEach(ArrayList.java:1596)

my service:

@Service
public class EmpresaService {

    private final EmpresaRepository empresaRepository;

    public List<Empresa> getAllEmpresas() {
        return empresaRepository.findAll();
    }

}

@Repository
public interface EmpresaRepository extends JpaRepository<Empresa, Long> {
    Optional<Empresa> findByRazaoSocial(String name);
    Optional<Empresa> findByCnpj(String cnpj);
}

my test class, I want to check if the method returns a list but this list is always empty or index out of bounds

@RunWith(MockitoJUnitRunner.class)
@SpringBootTest(classes = PetaApiApplication.class)
class EmpresaServiceTest {
    @Mock
    EmpresaRepository empresaRepository;

    @InjectMocks
    EmpresaService empresaService = new EmpresaService(empresaRepository);

    private final List<Empresa> empresas = new ArrayList<>();

    @Test
    public void should_Return_All_Empresas() {
        Empresa empresa1 = new Empresa(1L, "EMPRESA 1", "12345678");
        Empresa empresa2 = new Empresa(2L, "EMPRESA 2", "456");
        empresas.add(empresa1);
        empresas.add(empresa2);    
        when(empresaRepository.findAll()).thenReturn(empresas);

        List<Empresa> foundEmpresas = this.empresaService.getAllEmpresas();

        assertNotEquals(null, foundEmpresas);

        assertEquals("EMPRESA 1", foundEmpresas.get(0).getRazaoSocial());

        System.out.println(foundEmpresas.size());
        System.out.println(empresas.size());

    }

}
Share Improve this question asked Feb 1 at 10:30 GilmarGilmar 696 bronze badges 3
  • 1 EmpresaService does not have a constructor, you'll need to add one with EmpresaRepository empresaRepository as parameter and initialize empresaRepository. – Roar S. Commented Feb 1 at 11:54
  • Gilmar: Can you accept answer from @GeiiLvov instead, it gives more compact code, and my latest update is from his answer. BR – Roar S. Commented Feb 1 at 17:13
  • See "Corollary: Object life cycles and magic framework annotations" of stackoverflow/questions/74027324/… – it is exactly your code and problem (after you get rid of @SpringBootTest. – knittl Commented Feb 1 at 21:43
Add a comment  | 

2 Answers 2

Reset to default 2

@InjectMocks means that the mocked dependencies will be automatically injected, so you don't need to create an instance of EmpresaService using new EmpresaService(empresaRepository). Also, if you want to write a simple unit test using JUnit 5, you only need to use @ExtendWith(MockitoExtension.class) to automatically configure mocks marked with the @Mock annotation.

import .junit.jupiter.api.Test;
import .junit.jupiter.api.extension.ExtendWith;
import .mockito.InjectMocks;
import .mockito.Mock;
import .mockito.junit.jupiter.MockitoExtension;

@ExtendWith(MockitoExtension.class)
class EmpresaServiceTest {

    @InjectMocks
    private EmpresaService empresaService;

    @Mock
    private EmpresaRepository empresaRepository;

    private final List<Empresa> empresas = new ArrayList<>();


    @Test
    public void should_Return_All_Empresas() {
        Empresa empresa1 = new Empresa(1L, "EMPRESA 1", "12345678");
        Empresa empresa2 = new Empresa(2L, "EMPRESA 2", "456");
        empresas.add(empresa1);
        empresas.add(empresa2);
        when(empresaRepository.findAll()).thenReturn(empresas);

        List<Empresa> foundEmpresas = empresaService.getAllEmpresas();

        assertNotEquals(null, foundEmpresas);
        assertEquals("EMPRESA 1", foundEmpresas.get(0).getRazaoSocial());

        System.out.println(foundEmpresas.size());
        System.out.println(empresas.size());
    }
}

Update Used @ExtendWith(MockitoExtension.class) from @GeiiLvov in order to get more compact code. I asked OP to accept his answer instead, but I guess the missing constructor solved his problem. Answer from @GeiiLvov is the one to upvote.


I believe you're trying to unit test EmpresaService, hence this is not a Spring Boot test. Please try to change your test class like this:

@ExtendWith(MockitoExtension.class)
class EmpresaServiceTest {

    @Mock
    EmpresaRepository empresaRepository;

    @InjectMocks
    EmpresaService empresaService; // Mockito inits this


    @Test
    public void should_Return_All_Empresas() {
       // your test code
    }
}

And as I mentioned in a comment; you'll need a constructor in EmpresaService:

@Service
public class EmpresaService {

    private final EmpresaRepository empresaRepository;

    public EmpresaService(EmpresaRepository empresaRepository) {
       this.empresaRepository = empresaRepository;
    }
发布评论

评论列表(0)

  1. 暂无评论