我使用SpringBoot,我必须为一个函数编写单元测试,该函数通过TaskExecutor调用另一个私有函数。问题是单元测试无法覆盖私有功能。这是代码: threadconfig.vi可:
@Configuration
@EnableAsync
public class ThreadConfig {
@Bean(name = "taskExecutor")
public TaskExecutor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(1);
executor.setMaxPoolSize(1);
executor.initialize();
return executor;
}
}
Service.java:
@Service
public class Service {
@Autowired
@Qualifier("taskExecutor")
private TaskExecutor taskExecutor;
public String test() {
Runnable task = this::task;
taskExecutor.execute(task);
return "OK";
}
private void task(){
System.out.println("Test");
}
}
ServiceTest.java
@RunWith(SpringRunner.class)
public class ServiceTest {
@Mock(name = "taskExecutor")
private TaskExecutor taskExecutor;
@InjectMocks private Service service;
@Test
public void test() {
final String expected = "OK";
Mockito.doNothing().when(taskExecutor).execute(Matchers.any(Runnable.class));
assertEquals(expected, service.test());
}
}
测试可以覆盖test()函数但不能覆盖task()函数