简体   繁体   English

如何执行使用过的组件的代码而不是@Mock JUnit 测试中的结果?

[英]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. Service1Service2没有使用任何第三个服务,它只是执行了简单的逻辑。

@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 存储库中准备了一个完全可重现的代码示例 - 测试通过了。

If you want to use real instances of service1 and service2 you can use @Spy如果你想使用service1service2的真实实例,你可以使用@Spy

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM