JUnit Test. NullPointerException in @Inject of the interface

0

My problem is as follows.

I have a Java application whose beans I annotated with @Named and to do the dependency injection between those beans (whether @Controller, @Services ...) I use the @Inject notation.

So far so good. The problem comes when I want to do an @Inject in a test class which I have written down as follows:

package com.example.controller;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.fail;

import javax.inject.Inject;

import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;

import com.example.model.User;
import com.example.model.UserStateType;
import com.example.service.UserService;
import com.example.util.Utils;

@RunWith(SpringRunner.class)
@SpringBootTest
class UserActionCtrlTest {

    @Inject
    private UserService userService;
    @Inject
    private PasswordEncoder passwordEncoder;

    @Transactional
    @Test
    void testAddUser() {
        User user = new User();
        user.setNif("56665142L");
        user.setFirstname("FIRST_NAME");
        user.setLastname("LAST_NAME");
        user.setEmail("[email protected]");
        user.setName("NAME");
        user.setPassword(passwordEncoder.encode("PASSWORD"));
        user.setId(999999999L);
        user.setCreatedDate(Utils.getNow());
        user.setState(UserStateType.active);

        User compareUser = userService.addUser(user);
        assertNotNull(user);
        assertNotNull(compareUser);
        assertEquals(user, compareUser);
    }
}

When debugging in userService, which is the interface that contains the definition of the methods that userServiceImpl will implement, its content is null.

In the pom I have the necessary dependence to do the unit tests with Junit:

 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <version>2.0.0.RELEASE</version>
            <scope>test</scope>
    </dependency>
    
asked by Adrian Hidalgo Ejeda 28.03.2018 в 11:50
source

0 answers