我有一个Spring-boot应用程序,正在尝试为其创建单元测试用例。以下是我要运行的代码,我没有任何配置文件(仅用于注释),因此加载所有配置的主要类为ElastSearchBootApplication
类。由于某种原因,我看到以下错误。
@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());
失败了,我不知道原因...
答案 0 :(得分:2)
您必须在测试类中添加@ContextConfiguration注释以指定配置文件。
@ContextConfiguration(classes = ElastSearchBootApplication.class)
答案 1 :(得分:0)
尝试一下:
@RunWith(SpringRunner.class)
@SpringBootTest
public class LogSearchTest {
@MockBean
private RestHighLevelClient client;
@MockBean
private ExecutorService ALERT_POOL;
@Before
public void setUp() throws Exception {
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()));
}