繁体   English   中英

Spring 启动集成测试 - Mocking @Service 在应用程序上下文启动之前?

[英]Spring Boot Integration Testing - Mocking @Service before Application Context Starts?

我必须为微服务 X 创建一个集成测试,它从外部 sftp 服务器下载、处理和导入 csv 文件。 整个过程由 spring 引导调度程序任务启动,该任务启动 spring 批处理作业以处理和导入数据。 导入过程由 spring 批处理编写器完成,它是一个 restTemplate 存储库(因此它调用另一个微服务 Y 的发布请求)。

我已经设法模拟了 sftp 服务器,在其上放置了一个测试文件,当前的集成测试正在下载该文件。 https://github.com/stefanbirkner/fake-sftp-server-rule/

我的问题是,该任务将在应用程序上下文启动时立即安排,因此没有像 api 调用这样的触发器。 为了让整个集成测试正常工作,我必须模拟通过 restTemplate 调用调用外部微服务 Y 的部分。 此存储库在 spring 批处理写入器中调用,此存储库由作为 @Service 的 repositoryFactory 创建。 repositoryFactory 被注入到 spring 批量配置 class 中。

我已经尝试在测试 class 以及在我是 mocking 的单独测试配置中使用 @MockBean 注释,创建() function 工厂的模拟文件。 但在某些时候它不起作用,它仍然提供原始的 object,这会导致导入工作中断。

我还尝试使用 WireMock 库,但在这种情况下,它也没有捕获任何 api 调用,并且在某些时候会导致中断 sftp 套接字。 (?)

我希望有人可以帮助我。

目前的测试:

@NoArgsConstructor
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ContextConfiguration(classes = {JsonHalConfig.class})
@TestPropertySource(locations = "classpath:application-test.properties")
@TestMethodOrder(MethodOrderer.MethodName.class)
public class ImportIT {

    @ClassRule
    public static final FakeSftpServerRule sftpServer = new FakeSftpServerRule();
    private static final String PASSWORD = "password";
    private static final String USER = "username";
    private static final int PORT = 14022;

    @BeforeClass
    public static void beforeClass() throws IOException {
        URL resource = getTestResource();
        if (resource != null) {
            sftpServer.setPort(PORT).addUser(USER, PASSWORD);
            sftpServer.createDirectories("/home/username/it-space/IMPORT", "/home/username/it-space/EXPORT");
            sftpServer.putFile("/home/username/it-space/IMPORT/INBOX/testFile.csv",
                    resource.openStream());
        } else {
            throw new IOException("Failed to get test resources");
        }
    }

    private static URL getTestResource() {
        return ImportIT.class.getClassLoader().getResource("testFile.csv");
    }

    @Test
    public void test_A_() throws IOException, RepositoryException {
        assertTrue(true);
    }
}

我尝试了以下配置类

(包含在@ContextConfiguration 中)

@Configuration/@TestConfiguration
public class RepositoryTestConfig {
    @Bean
    @Primary
    public IRepositoryFactory repositoryFactory() {
        IRepositoryFactory repositoryFactory = mock(IRepositoryFactory.class);
        IRepository repository = mock(IRepository.class);
        when(repositoryFactory.create(anyString())).thenReturn(repository);
        return repositoryFactory;
    }
}

(作为测试类中的 static class)

    @TestConfiguration/@Configuration
    public static class RepositoryTestConfig {
        @MockBean
        private IRepositoryFactory repositoryFactory;

        @PostConstruct
        public void initMock(){
            IRepository repository = mock(IRepository.class);
            Mockito.when(repositoryFactory.create(anyString())).thenReturn(
                    repository
            );
        }
    }

更新 27.08.2021我有一个 RestConfig @Component 在其中创建了一个新的 RestTemplateBuilder。 我试图@MockBean 这个组件来提供一个 RestTemplateBuilder 模拟并注入一个 MockRestServiceServer object 来捕捉传出的 api 调用。 但不幸的是,它不能像方面那样工作。 我错过了什么吗? 我还尝试创建一个“TestRestController”来触发任务的调度,但它从不提供模拟......

我通常直接在我的测试类中使用@MockBean ,并直接在那里注入专用(但模拟的)存储库,而不是在测试配置中创建它。 我还通过@ContextConfiguration添加了测试配置 class ,因此它被加载到当前测试上下文中。

在我的测试中,我只是以标准方式使用 mockito,并根据需要为专用测试方法准备模拟部件。

这是一个示例片段:

// ... do some imports ...
@RunWith(SpringRunner.class)
@ContextConfiguration(classes= {XYZSomeWantedClazz.class, DemoXYZMockTest.SimpleTestConfiguration.class})
@ActiveProfiles({Profiles.TEST})
public class DemoXYZMockTest {
   //...
   @MockBean
   private DemoRepository mockedDemoRepository;
   // ...
   @Test
   public void testMethodName() throws Exception{
       /* prepare */
       List<WantedEntityClazz> list = new ArrayList<>();
       // add your wanted data to your list

       // apply to mockito:
       when(mockedDemoRepository.findAll()).thenReturn(list);

       /* execute */
       // ... execute the part you want to test...
 
       /* test */
       // ... test the results after execution ...

   }


   @TestConfiguration
   @Profile(Profiles.TEST)
   @EnableAutoConfiguration
   public static class SimpleTestConfiguration{
      // .. do stuff if necessary or just keep it empty
   }

}

有关完整(旧 Junit4)工作测试示例,请查看: https://github.com/mercedes-benz/sechub/blob/3f176a8f4c00b7e8577c9e3bea847ecfc91974c3/sechub-administration/src/test/java/com/daimler/daimler域/管理/注册/SignupAdministrationRestControllerMockTest.java

暂无
暂无

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

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