Spring Boot 服务层测试使用 SpringMockk

时间:2021-06-22 10:09:39

标签: java spring spring-boot mockk

我正在使用 Kotlin 开发一个 Spring Boot 项目。

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

这是我的 RecipeService 类:

@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
    
    ......

}

我的测试类如下所示:


@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 中正确测试我的服务层?

谢谢!

1 个答案:

答案 0 :(得分:0)

使用 @Import 让 Spring Test 生成您的 RecipeService 的实例,否则,如异常所示,没有任何可自动装配的内容:

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