简体   繁体   中英

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!

简单但不是很好 - 将注释 @ComponentScan 添加到 UserTest 类

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM