Spring启动应用程序在我运行时工作,但在测试时会掉落

时间:2017-07-05 11:43:45

标签: java spring tdd

我有一个带有一个控制器的简单弹簧应用程序

@RestController
public class UserController {

//  @Autowired
//  UserServiceImpl userService;

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

当我开始它时它起作用。如果我取消注释@Autowired并使用UserService运行第一个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)}

测试类

@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语句运行test,测试执行时没有错误。我知道问题出在UserServiceImpl,但我不知道它是什么。我需要纠正什么?

1 个答案:

答案 0 :(得分:1)

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

@Autowired
UserService userService;

此外,您应该从@Service界面

中删除UserService
相关问题