[英]How to execute the code of a used Component instead @Mock the results in JUnit Tests?
I have a @Component
class that contains some @Inject
components to perform some code logic.我有一个
@Component
class ,其中包含一些@Inject
组件来执行一些代码逻辑。 In my Test, I would like to execute that logic instead Mock the results.在我的测试中,我想执行该逻辑而不是模拟结果。 I don't want to import
spring-boot-starter-test
because will overload the dependencies and generate conflicts.我不想导入
spring-boot-starter-test
因为会重载依赖并产生冲突。
The Service1
and Service2
doesn't use any third services, it's has just executed simple logic. Service1
和Service2
没有使用任何第三个服务,它只是执行了简单的逻辑。
@Component
public class MainService {
@Inject
private Service1 service1;
@Inject
private Service2 service2;
}
---------------- Test Class ----------------
@RunWith(MockitoJUnitRunner.class)
public class SomeTest {
@Mock
private Service1 service1;
@Mock
private Service2 service2;
@InjectMocks
private MainService mainService;
@Before
public void startUp() {
MockitoAnnotations.initMocks(this);
}
@Test
public void test1() {
Mockito.when(service1.function).thenReturn(...);
Mockito.when(service2.function).thenReturn(...);
// How to provide real execution instead Mock the results?
mainService.start();
// asserts...
}
}
The best approach would be just using the constructor or accessor injection instead of field injection (read more here or here ), but if you really need to stick to the field injection, simply replace the @Mock
annotations with @Spy
annotations like so:最好的方法是使用构造函数或访问器注入而不是字段注入( 在此处或此处阅读更多内容),但如果您真的需要坚持使用字段注入,只需将
@Mock
注释替换为@Spy
注释,如下所示:
@Spy
private Service1 service1;
@Spy
private Service2 service2;
or (if the ServiceX
classes do not have a default constructor):或(如果
ServiceX
类没有默认构造函数):
@Spy
private Service1 service1 = new Service1(...);
@Spy
private Service2 service2 = new Service2(...);
Those fields will be used by Mockito when you call initMocks
and will be injected into the fields annotated with @InjectMocks
.当您调用
initMocks
时,这些字段将由 Mockito 使用,并将被注入到带有@InjectMocks
注释的字段中。 No behavior mocking required, the actual ServiceX
classes code will be called.无需行为 mocking,将调用实际的
ServiceX
类代码。
I've prepared a fully reproducible code example in a GitHub repository here - the test passes.我在GitHub 存储库中准备了一个完全可重现的代码示例 - 测试通过了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.