Spring应用程序运行但无法在测试时创建bean

时间:2018-04-03 17:52:23

标签: java spring unit-testing

我正在用Spring编写应用程序,我想使用单元测试。 当我运行我的应用程序时,不会发生错误或异常。但是当我想要进行“gradle test”时整个地方都有UnsatisifiedDependencyExceptions。

@RunWith(SpringJUnit4ClassRunner.class)
@WebMvcTest(AuthenticationController.class)
@ContextConfiguration(classes = {MockMvc.class, TokenHandler.class, LoginService.class, UserService.class})
public class AuthenticationControllerTest {

    @Autowired private MockMvc mockMvc;
    @Autowired private TokenHandler tokenHandler;
    @Autowired private LoginService loginService;
    @Autowired private UserService userService;

    @Value("${server.port}") private Integer serverPort;

    private String username;
    private String email;
    private String password;

    private UserEntity userEntity;
    private String token;

    @Before
    public void setUp(){
        this.username = UUID.randomUUID().toString();
        this.email = this.username + "@test.com";
        this.password = UUID.randomUUID().toString();
    }

    @Test
    public void a0_register() throws Exception {
        RegisterDTO registerDTO = new RegisterDTO();
        registerDTO.setUsername(this.username);
        registerDTO.setEmail(this.email);
        registerDTO.setPassword(this.password);

        this.mockMvc.perform(
                MockMvcRequestBuilders.post(URI.create("/authentication/register"))
                    .content(JSON.asJsonString(registerDTO))
                    .contentType(MediaType.APPLICATION_JSON_UTF8))
        .andExpect(status().isOk())
        .andExpect(content().string("0"));

        this.userEntity = this.userService.findAll().stream().filter(e->e.getEmail().equals(email)).findFirst().orElse(null);

        assertNotNull(userEntity);
    }
}

以下是抛出异常之一的示例:

Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'loginService': Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'net.roomono.administration.Database.Repository.Log.LoginRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:729)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:192)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1270)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1127)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:502)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:312)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:310)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200)
at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:251)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1138)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1065)
at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:815)
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:721)
... 67 more

1 个答案:

答案 0 :(得分:1)

这条线需要修复:

@ContextConfiguration(classes = {MockMvc.class, TokenHandler.class, LoginService.class, UserService.class})

不要在此列出服务或bean类。而是创建一个配置类来配置bean。如:

@Configuration
public class AppConfig {
  @Bean
  public LoginService loginService() {
    return new LoginService();
  }
  ...
}

然后,使用它:

@ContextConfiguration(classes = {AppConfig.class})