Spring 引导应用程序在我 运行 时工作,但在我测试时下降

Spring boot app works when I run it, but falls when I test it

我有一个简单的 spring 应用程序,只有一个控制器

@RestController
public class UserController {

//  @Autowired
//  UserServiceImpl userService;

  @RequestMapping(value="/getUser", method = RequestMethod.GET)
  public String getUser(){
//    return userService.greetUser();
    return "Hello user";
  }

当我启动它时它会起作用。如果我使用 UserService 取消注释 @Autowired 和 运行 第一个 return 语句,它也有效。

我的服务界面

@Service
public interface UserService {
  String greetUser();
  void insertUsers(List<User> users);
}

和实施

@Service
public class UserServiceImpl implements UserService{

  @Override
  public String greetUser() {
    return "Hello user";
  }
}

但是当我测试它时,该应用程序出现以下错误

java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userController': Unsatisfied dependency expressed through field 'userService'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.example.demo.service.UserServiceImpl' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.example.demo.service.UserServiceImpl' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

测试class

@RunWith(SpringRunner.class)
@WebMvcTest
public class DemoApplicationTests {

  @Autowired
  private MockMvc mockMvc;

    @Test
  public void shouldReturnHelloString() throws Exception{
      this.mockMvc
      .perform(get("/getUser"))
      .andDo(print())
      .andExpect(status().isOk())
      .andExpect(content().string("Hello user"));
  }
}

此外,如果我删除

//  @Autowired
//  UserServiceImpl userService;

和 运行 测试第二个 return 语句,测试执行没有错误。我知道问题出在 UserServiceImpl,但我不知道它是什么。我需要纠正什么?

您应该尝试通过接口而不是实现来自动装配您的 bean

@Autowired
UserService userService;

而且您还应该从 UserService 界面中删除 @Service