我有一个简单的健康控制器定义如下:
@RestController
@RequestMapping("/admin")
public class AdminController {
@Value("${spring.application.name}")
String serviceName;
@GetMapping("/health")
String getHealth() {
return serviceName + " up and running";
}
}
以及用于测试它的测试类:
@WebMvcTest(RedisController.class)
class AdminControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
public void healthShouldReturnDefaultMessage() throws Exception {
this.mockMvc.perform(get("/admin/health"))
.andDo(print())
.andExpect(status().isOk())
.andExpect(content().string(containsString("live-data-service up and running")));
}
}
运行测试时,我收到以下错误信息:
***************************
APPLICATION FAILED TO START
***************************
Description:
Field configuration in com.XXXX.LiveDataServiceApplication required a bean of type 'com.XXXXX.AppConfiguration' that could not be found.
The injection point has the following annotations:
- @org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'com.XXXX.AppConfiguration' in your configuration.
以下是与Spring Boot主应用程序类位于同一包中的AppConfiguration.java
:
@Configuration
@EnableConfigurationProperties
@ConfigurationProperties
public class AppConfiguration {
@Value("${redis.host}")
private String redisHost;
@Value("${redis.port}")
private int redisPort;
@Value("${redis.password:}")
private String redisPassword;
...
// getters and setters come here
主类:
@SpringBootApplication
public class LiveDataServiceApplication {
@Autowired
private AppConfiguration configuration;
public static void main(String[] args) {
SpringApplication.run(LiveDataServiceApplication.class, args);
}
@Bean
public RedisConnectionFactory redisConnectionFactory() {
RedisStandaloneConfiguration redisConfiguration = new RedisStandaloneConfiguration(configuration.getRedisHost(), configuration.getRedisPort());
redisConfiguration.setPassword(configuration.getRedisPassword());
return new LettuceConnectionFactory(redisConfiguration);
}
}
如果我将测试类中的注释修改为以下内容,则测试通过:
@SpringBootTest
@AutoConfigureMockMvc
class AdminControllerTest {
....
我错过了什么?
LiveDataServiceApplication
类中为AppConfiguration
执行自动装配。但是你没有将AppConfiguration
类标记为bean。 - Deepak Kumar@Service
来为类AppConfiguration
进行注释。 - Deepak Kumar@Configuration
定义了它,这个注解别名是@Component
。这不够吗? - belgoros