作者:txy001美丽人生_618 | 来源:互联网 | 2022-12-05 10:56
我有一个弹簧启动应用程序,正在尝试为其创建单元测试用例。下面是我要运行的代码,我没有任何配置文件(仅使用注释),因此加载所有配置的主类是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
from 的值Environment
并将其放置为@Scheduled(fixedRate = ${some.value.defined})
更新
我可以运行测试,但没有正确的顺序。理想情况下,我希望setUp
首先运行。但其运行第二。另外线路when(client.search(anyObject())).thenReturn(getResponse());
失败了,我不知道原因...
1> 小智..:
您必须在测试类中添加@ContextConfiguration注释以指定配置文件。
@ContextConfiguration(classes = ElastSearchBootApplication.class)