【问题标题】:Spring Boot testing with different service class具有不同服务类的 Spring Boot 测试
【发布时间】:2019-02-22 16:32:28
【问题描述】:

我有一个非常基本的问题,如果之前有人问过,我深表歉意。我担心我可能用错了词,这是我第一次参加 Spring 的牛仔竞技表演。

我有一个 RestController 声明如下:

@RestController
class TelemetryController {

    @Autowired
    lateinit var service: TelemetryService
    //...
}

在我们的main 模块中具体实现TelemetryService

@Service
class ConcreteTelemetryService : TelemetryService {
   // some production code
}

然后,我想在测试期间在我的控制器中使用一项服务(在我们的 test 模块中:

@Service
class TestingTelemetryService : TelemetryService {
   // some test code using local data
}

重要的是,我不想为此使用 Mockito,因为测试的实施需要非常具体的设置,不适合 Mockito。

我的测试是这样声明的:

@RunWith(SpringRunner::class)
@SpringBootTest
@AutoConfigureMockMvc
class HowDoInjectServiceExampleTest {

    @Autowired
    lateinit var mockMvc: MockMvc
}

在这种情况下,如何在我的控制器中获取我的TestingTelemetryService

【问题讨论】:

    标签: spring unit-testing testing kotlin


    【解决方案1】:

    有多种方法可以实现这一点,但我建议使用 Spring Profiles。

    在具体实现中使用默认配置文件。如果未指定配置文件,将使用此 bean。

    @Profile("default")
    @Service
    class ConcreteTelemetryService : TelemetryService {
       // some production code
    }
    

    将配置文件“test”添加到测试实现中。

    @Profile("test)
    @Service
    class TestingTelemetryService : TelemetryService {
       // some test code using local data
    }
    

    现在您可以开始测试了

    -Dspring.profiles.active=test
    

    在此处阅读有关个人资料的更多信息:

    https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-profiles.html

    【讨论】:

    • 作为附录,我在测试模块的两个资源目录中的application.properties 文件中添加了spring.profiles.active=test。似乎比在 IDEA 中使用命令行参数和插槽好一点。
    【解决方案2】:

    如果您的 TestingTelemetryServiceHowDoInjectServiceExampleTest 在同一个包中,那么您可以简单地自动装配测试 bean,例如

    @RunWith(SpringRunner::class)
    @SpringBootTest
    @AutoConfigureMockMvc
    class HowDoInjectServiceExampleTest {
    
        @Autowired
        lateinit var mockMvc: MockMvc
    
        @Autowired
        var service: TestingTelemetryService
    }
    

    如果不是,那么您应该定义一些 TestConfiguration 并以编程方式定义带有服务名称的 bean,并在测试中使用 @Qualifier 来解析要使用的 bean(在您的情况下是它的测试 bean)

    【讨论】:

    • 这对我不起作用,虽然所有东西都在同一个包中。
    猜你喜欢
    • 2021-03-15
    • 1970-01-01
    • 2017-10-30
    • 2018-08-31
    • 1970-01-01
    • 1970-01-01
    • 2020-03-24
    • 2020-04-23
    • 2022-10-24
    相关资源
    最近更新 更多