gpt4 book ai didi

SpringRunner 无法检测配置

转载 作者:行者123 更新时间:2023-12-03 18:35:16 29 4
gpt4 key购买 nike

我有一个 spring-boot 应用程序,我正在尝试为其创建单元测试用例。下面是我尝试运行的代码,我没有任何配置文件(仅使用注释)所以加载所有配置的主类是 ElastSearchBootApplication类(class)。出于某种原因,我看到以下错误。

@ComponentScan(basePackages = "com.somename")
@SpringBootApplication
@EnableScheduling
public class ElastSearchBootApplication {

private static final Logger LOG = LoggerFactory.getLogger(ElastSearchBootApplication.class);

public static void main(String[] args) {
SpringApplication.run(ElastSearchBootApplication.class, args);
}

@Autowired
private ElastSearchLogLevel logsSearch;

@Scheduled(fixedRate = 120000)
public void scheduledSearchLogs() {
...

测试类:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = ElastSearchBootApplication.class)
public class LogSearchTest {

@Mock
private RestHighLevelClient client;
@Mock
private ExecutorService ALERT_POOL;

@Before
public void setUp() throws Exception {
client = mock(RestHighLevelClient.class);
ALERT_POOL = mock(ExecutorService.class);

try {
when(client.search(anyObject())).thenReturn(getResponse());
} catch (Exception e) {
// I see NullPointerException but both the instances are available here
e.printStackTrace();
}
doNothing().when(ALERT_POOL.invokeAll(anyObject()));
}

尝试运行 spring-boot 测试时,我看到以下错误:
org.springframework.boot.test.context.SpringBootTestContextBootstrapper buildDefaultMergedContextConfiguration
INFO: Neither @ContextConfiguration nor @ContextHierarchy found for test class [com.somename.search.LogSearchTest], using SpringBootContextLoader
org.springframework.test.context.support.AbstractContextLoader generateDefaultLocations
INFO: Could not detect default resource locations for test class [com.somename.search.LogSearchTest]: no resource found for suffixes {-context.xml, Context.groovy}.
org.springframework.test.context.support.AnnotationConfigContextLoaderUtils detectDefaultConfigurationClasses
INFO: Could not detect default configuration classes for test class [com.somename.search.LogSearchTest]: LogSearchTest does not declare any static, non-private, non-final, nested classes annotated with @Configuration.
  • 我看到了 @SpringBootTest用于集成测试,那么我可以将它用于单元测试吗?如果我删除它,那么我会得到另一组看起来相似的异常。如果没有 SpringBootTest,我会对运行这个测试用例更感兴趣。
  • 为什么我的测试用例说缺少某些配置。在线示例讨论了我没有的 xml 文件。那么我在这里错过了什么?
  • 我可以动态传递 fixedRate 的值吗?来自 Environment并把它像 @Scheduled(fixedRate = ${some.value.defined})

  • 更新

    我可以运行测试,但没有正确的顺序。理想情况下,我希望 setUp先运行。但它的运行第二。也行 when(client.search(anyObject())).thenReturn(getResponse());失败了,我不明白原因......

    最佳答案

    您必须将注释 @ContextConfiguration 添加到您的测试类以指定配置文件。

    @ContextConfiguration(classes = ElastSearchBootApplication.class)

    关于SpringRunner 无法检测配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52274066/

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