gpt4 book ai didi

java - SpringBoot 和 JUnit - 测试服务类 - 无法加载应用程序上下文

转载 作者:行者123 更新时间:2023-12-05 05:14:17 24 4
gpt4 key购买 nike

我正在尝试对 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 应该从应用程序加载所有应用程序上下文测试环境...

最佳答案

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

要么删除显式classes参数-SpringRunner将在当前包和父包中搜索SpringBootApplication注释类,并搜索内部配置类,

或将其添加到您的@SpringBootTest

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

关于java - SpringBoot 和 JUnit - 测试服务类 - 无法加载应用程序上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52744757/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com