Search code examples
javaspringspring-bootautowiredspring-boot-test

Cannot use Autowired in a test class but able to use it in an implementation class?


I'm trying to testing a @Controller class where there is a List from a pojo's. I can use @Autowired in another @RestController class to wire the controller, but in the same situation I can't do it into a Test.

User.java

@Data //from lombok
public class User  {
    private String Id;
    private String email;

    //constructor + getters and setters
}

UserContrell3.java

@Controller
public class UserController {

    private List<User> userRepo = new ArrayList<>();

    public UserController() {}

    public List<User> readAll() {
        return userRepo;
    }

    public void add(User user) {
        userRepo.add(user);
    }
}

In the next class, UserResource.java I can do @Autowired

@RestController
@RequestMapping(UserResource.USER)
public class UserResource {
    public static final String USER = "/users";

    private UserController userController;

    @Autowired
    public UserResource(UserController userController) {
        this.userController = userController;
    }

    @GetMapping
    public List<User> readAll() {
        return userController.readAll();
    }

    @PostMapping
    public void addUser(@RequestBody User user) {
        userController.add(user);
    }
}

However, into the test class UserTest.java. I can't:

@SpringBootTest(classes = {cat.jhz.Main.MainApp.class})
@TestPropertySource("classpath:test.properties")
public class UserTest {

    // @Autowired **//NOT HERE** --> ERROR
    private UserController userRepo;

    @Autowired **//AND NOT HERE** --> ERROR
    public UserResource(UserController userController) {
        this.userController = userController;
    }

    @Test
    void testAddUserToUserController() {
        ...
    }

}

The error message is Could not autowire. No beans of 'UserController' type found.

Any idea?

Thanks in advance!


Solution

  • Simply but not so great - add annotation @ComponentScan to UserTest class