2017-08-28 45 views
3

我正在爲SystemLoggingService編寫單元測試,並嘲笑對其存儲庫的所有調用。 我使用SpringJPA存儲庫。如何使用不實現equals的參數來模擬方法調用?

@Repository 
public interface SystemLoggingRepository extends PagingAndSortingRepository<SystemLogEntity, Long>, JpaSpecificationExecutor<SystemLogEntity> { 
} 

對於服務方法findAll(Searchable searchable,Pageable pageable)的一個單元測試我需要模擬存儲庫方法findAll(Specification<T> spec, Pageable pageable)

作爲一個看到,所述Searchable對象被變換到服務邏輯內的JPA Specifications對象。

問題是我的服務邏輯將傳遞到存儲庫方法的JPA的Specifications類不執行equals()

換句話說,我不能嘲笑庫方法非常精確,因爲我必須使用Matchers.any(Specifications.class)

BDDMockito.given(systemLoggingRepository.findAll(Matchers.any(Specifications.class), Matchers.eq(pageRequest))).willReturn(...) 

如何不好是本作的單元測試的質量,或者這是常見的做法?對這個問題有什麼不同的解決方法? Specifications對象是一個Spring框架類。只是添加equals()方法不是一個選項。

回答

2

除的答案@VolodymyrPasechnyk你可能會想到將創建Specifications對象的責任提取到一個單獨的類,這將是另一個類依賴關係到您的CUT。

+0

是的,這是一個想法。目前我不知道如何測試這個創建過程,但它標有一個問題。 –

+0

@HerrDerb這是cleares的標誌,應該移動到它自己的單位... –

+0

是的,這是有道理的。如果我這樣做的話,我也可以使用類匹配器Matchers.any(Specifications.class)來進行嘲諷而沒有任何問題。我看到這個對嗎? –

3

您可以嘗試捕捉與規格:

ArgumentCaptor<Specifications> specificationsCaptor = ArgumentCaptor.forClass(Specifications.class); 
BDDMockito.given(systemLoggingRepository.findAll(specificationsCaptor.capture(), Matchers.eq(pageRequest))).willReturn(...) 

然後驗證捕獲值:

Specifications capturedSpecifications = specificationsCaptor.getValue(); 
assertThat(capturedSpecifications.getSomeProperty(), ...) 

您可以在這裏找到更多的信息:https://static.javadoc.io/org.mockito/mockito-core/2.8.47/org/mockito/Mockito.html#15

相關問題