我有一个spring引导应用程序,它试图创建单元测试用例。下面是我试图运行的代码,我没有任何配置文件(只使用注释),所以加载所有配置的主类是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启动测试时,我看到了以下错误:
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
,我会更感兴趣地运行这个测试案例。fixedRate
动态传递Environment
的值,并将其放在@Scheduled(fixedRate = ${some.value.defined})
中更新
我可以运行测试,但没有适当的命令。理想情况下,我希望setUp
首先运行。但它的运行第二。另外,when(client.search(anyObject())).thenReturn(getResponse());
的线路失败了,我不明白原因.
发布于 2018-09-11 03:01:39
您必须将注释@ContextConfiguration添加到您的测试类中,以指定配置文件。
@ContextConfiguration(classes = ElastSearchBootApplication.class)
发布于 2018-09-11 04:06:22
试试这个:
@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()));
}
https://stackoverflow.com/questions/52274066
复制相似问题