簡體   English   中英

如何對必須傳遞 class 具有可訪問性 scope 的 bean 的服務進行單元測試? [史波克]

[英]How to unit test service where you have to pass bean that class is of accessibility scope? [Spock]

我嘗試使用六邊形方法,其中我的域 package 我有視圖 scope 的類。

但是我遇到了一個問題,如何模擬由於視圖訪問而無法使用的東西。

我應該@Autowire那個bean但是我意識到我仍然不能使用和傳遞其中的一些作為模擬和rest作為自動裝配的bean。

我不認為更改訪問視圖以進行測試是一個很好的解決方案。

所以我正在尋找一個解決方案,如何以正確的方式做到這一點。 有任何想法嗎?

下面是我的例子:

@Service
@RequiredArgsConstructor
public class RecipeService {

private final RecipeRepository recipeRepository; //view scope access
private final UserService userService; //public access

public Optional<Recipe> getRecipeById(Long id) {
        return recipeRepository.findById(id);
}

///////////////
@Repository
interface RecipeRepository extends JpaRepository<Recipe, Long> {
Optional<Recipe> findById(Long recipeId);
}

並測試:

class RecipeServiceTest extends Specification {

private RecipeRepository recipeRepository = Mock()
private UserService userService = Mock()

void setup() {
        recipeService = new RecipeService(recipeRepository, userService)
}

以這種方式我收到錯誤: java.lang.IllegalAccessError: tried to access class.recipe.domain.RecipeRepository from class.recipe.service.RecipeServiceTest

[編輯]

樹下

└───src
    ├───main
    │   ├───java
    │   │   └───com
    │   │       └───app
    │   │           └───example
    │   │               │   
    │   │               ├───recipe
    │   │               │   ├───controller
    │   │               │   └───domain
    │   │               │           RecipeRepository.java // visible scope
    │   │               │           RecipeService.java // visible public
    └───test
        ├───groovy
        │   └───com
        │       └───app
        │           └───example
        │               ├───recipe
        │               │   ├───controller
        │               │   └───domain
        │               │           RecipeServiceTest.groovy

我會將 recipeRepository(以及 userService)作為參數傳遞給 RecipeService,因此 RecipeService 和 RecipeRepository 不會緊密耦合。 然后你可以模擬 recipeRepository

public class RecipeService (RecipeRepository recipeRepository,UserService userService) {   
public Optional<Recipe> getRecipeById(Long id) {
        return recipeRepository.findById(id);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM