【问题标题】:SpringBoot and JUnit - Testing Service class - Failed to load Application ContextSpringBoot 和 JUnit - 测试服务类 - 无法加载应用程序上下文
【发布时间】:2018-10-10 16:21:13
【问题描述】:

我正在尝试对 Spring Boot 应用程序中的服务类运行单元测试

我想试试这个测试

@RunWith(SpringRunner.class)
@SpringBootTest(classes=Application.class) //my @SpringBootApplication class
public class UserServiceTest { //i'm testing my UserService implementation

    @TestConfiguration
    static class UserServiceContextConfiguration {


        @Bean
        public IUserService service() {
            return new UserService();
        }

    }

    @Autowired
    private IUserService service;

    @MockBean
    private UserRepository repository;

    @Before
    public void setUp() {
        User me = new User();

        me.setEmail("admin@admin.com");

        Mockito.when(repository.findByEmail(me.getEmail())).thenReturn(me);
    }

    @Test
    public void whenValidEmail_thenFindUser() {
        String email = "admin@admin.com";
        User found = service.findByEmail(email);

        assertThat(found.getEmail()).isEqualTo(email);
    }

}

但是在启动测试时我得到了这个异常

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.myapp.service.UserServiceTest': Unsatisfied dependency expressed through field 'service'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.myapp.service.interfaces.IUserService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

也许我不清楚,但@TestConfiguration 应该允许我从应用程序定义我的 bean 以在测试中使用它们,@SpringBootTest 应该从应用程序加载所有应用程序上下文以用于测试环境...

【问题讨论】:

    标签: java spring-boot junit


    【解决方案1】:

    通过提供classes=Application.class,您关闭了内部配置类的自动扫描。

    要么去掉显式的classes参数——SpringRunner会在当前包和父包中搜索SpringBootApplication注解的类,也会搜索内部配置类,

    或将其添加到您的@SpringBootTest

    @SpringBootTest(classes= {Application.class, UserServiceContextConfiguration.class })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-17
      • 1970-01-01
      • 2013-02-03
      • 2018-07-11
      • 2019-08-25
      • 2015-04-27
      • 1970-01-01
      • 2012-01-20
      相关资源
      最近更新 更多