我正在尝试在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应该从应用程序为测试环境加载所有应用程序上下文。
答案 0 :(得分:2)
通过提供classes=Application.class
,您可以关闭内部配置类的自动扫描。
要么删除显式类参数-SpringRunner都会在当前包和父包中搜索SpringBootApplication带注释的类,还搜索内部配置类,
或将其添加到您的@SpringBootTest
@SpringBootTest(classes= {Application.class, UserServiceContextConfiguration.class })