[英]mock objects null for spring service class unit test
I have Spring Service class with multiple constructor:我有 Spring 服务 class 与多个构造函数:
@Service("async")
public class AsyncProcessor extends Processor {
private final JobRunner JobRunner;
private final ExecutorService executorService;
@Autowired
public AsyncProcessor(final MyRepo MyRepo,
final JobRunner JobRunner) {
this(MyRepo, JobRunner, 1, 1, 60);
}
public AsyncProcessor(final MyRepo MyRepo,
final JobRunner JobRunner,
@Value("${processor.corePoolSize:1}") final int corePoolSize,
@Value("${processor.maxPoolSize:1}") final int maxPoolSize,
@Value("${processor.keepAliveTime:60}") final int keepAliveTime) {
super(MyRepo);
this.JobRunner = JobRunner;
this.executorService = new ThreadPoolExecutor(corePoolSize, maxPoolSize, keepAliveTime, SECONDS, new LinkedBlockingQueue<>());
}
}
I am using Junit 5 to create a service test using mocked dependencies but tripping up with an error which I am not able to solve:我正在使用 Junit 5 使用模拟依赖项创建服务测试,但出现我无法解决的错误:
here is my test class:这是我的测试 class:
@ExtendWith(MockitoExtension.class)
public class MyTest {
@Mock
private MyRepo repo;
@Mock
private JobRunner jobRunner;
@Mock
private ExecutorService executorServiceMock;
@InjectMocks
private AsyncProcessor processor = new AsyncProcessor(repo, jobRunner);
@Test
public void shouldSubmitTaskOnExecutor() {
}
}
I am getting null on the mocked repo and job runner fields and don't know why.我在模拟的 repo 和 job runner 字段上得到 null 并且不知道为什么。 The issue started when I added the second constructor with the additional spring property params.
当我使用附加的 spring 属性参数添加第二个构造函数时,问题就开始了。
Any ideas?有任何想法吗?
I think the new keyword is messing things up.我认为新的关键字把事情搞砸了。 Create a Spring @Configuration class which has a @Bean annotated method that returns the async processor generated from the newly added constructor.
创建一个 Spring @Configuration class ,它有一个 @Bean 注释方法,该方法返回从新添加的构造函数生成的异步处理器。 Your test can then autowire it, without the constructor call.
然后,您的测试可以自动装配它,而无需调用构造函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.