Spring 使用 SpringMockk 启动服务层测试

Spring Boot service layer test with SpringMockk

我正在使用 Kotlin 开发 Spring 引导项目。

我目前正在尝试编写我的单元测试,因此我正在使用 Mockk,尤其是 springmockk。

这是我的 RecipeService class:

@Service
class RecipeService(
    private val recipeRepository: RecipeRepository,
    private val recipeMongoTemplateRepository: RecipeMongoTemplateRepository
) {

    @Autowired
    private lateinit var categoryService: CategoryService

    @Autowired
    private lateinit var courseService: CourseService

    @Autowired
    private lateinit var dietService: DietService
    
    ......

}

我的测试 class 看起来像这样:


@ExtendWith(SpringExtension::class, MockKExtension::class)
class RecipeServiceTest {

    @MockkBean
    private lateinit var recipeRepository: RecipeRepository

    @MockkBean
    private lateinit var recipeMongoTemplateRepository: RecipeMongoTemplateRepository

    @Autowired
    private lateinit var recipeService: RecipeService

    @Test
    fun test() {
        recipeService.getAll()
    }
}

在我的服务中尝试注入模拟存储库时,我遇到了以下问题:

org.springframework.beans.factory.UnsatisfiedDependencyException:创建名称为 'nl.whatsonthemenu.backend.recipe.RecipeServiceTest' 的 bean 时出错:通过字段 'recipeService' 表示的不满足的依赖关系;嵌套异常是 org.springframework.beans.factory.NoSuchBeanDefinitionException:没有可用类型 'nl.whatsonthemenu.backend.recipe.RecipeService' 的符合条件的 bean:预计至少有 1 个符合自动装配候选条件的 bean。依赖注解:{@org.springframework.beans.factory.annotation.Autowired(required=true)}

有人知道问题出在哪里吗?或者我如何使用 Mockk 在 Spring 中正确测试我的服务层?

谢谢!

使用 @Import 让 Spring 测试生成您的 RecipeService 的一个实例,否则,没有任何内容可以自动装配,因为异常指示:

@ExtendWith(SpringExtension::class, MockKExtension::class)
@Import(RecipeService::class)
class RecipeServiceTest {