簡體   English   中英

為什么在使用 HTTPGraphQLTester 和 TestEntityManager 的 Spring-Boot 集成測試中我的數據不能持久化/不可訪問

[英]Why is my data not persisted/accessible in an Spring-Boot integration-test with HTTPGraphQLTester and TestEntityManager

我有一個基本的 Spring-Boot 應用程序,其中包含一些 GraphQL 端點和一個 Postgres 數據庫,我想對一個端點運行集成測試。 當我通過 Postman 手動發送請求時,它應該通過 ID 找到一個實體並且這樣做沒有問題。但是當我為 controller 編寫集成測試時它沒有。 在使用TestEntityManager (或直接使用JpaRepository )之后,數據似乎被保存了,我用它的 ID 取回了實體。 然后我將該 ID 粘貼到使用HttpGraphQlTester的查詢中,該查詢失敗並返回空結果/null。 我使用調試器對其進行跟蹤,發現當端點調用存儲庫以檢索具有給定 ID 的實體時,它會得到 null,或者當我查看所有存儲庫內容時,它只是一個空列表。 所以我的數據似乎可以在我的測試中訪問,但不能在我的回購/服務中訪問。 任何指針將不勝感激。

測試

@SpringBootTest
@AutoConfigureHttpGraphQlTester
@AutoConfigureTestEntityManager
@Transactional
public class BackboneTreeControllerTest {

  @Autowired
  HttpGraphQlTester tester;

  @Autowired
  private TestEntityManager testEntityManager;

  @Test
  void findTaxon() {
    Taxon taxon = Taxon.builder()
      .path(Arrays.asList("path", "to", "taxon"))
      .nameCanonical("Cocos nucifera")
      .authorship("Me")
      .extinct(false)
      .numDescendants(1l)
      .numOccurrences(1l)
      .build();

    Taxon savedTaxon = testEntityManager.persistFlushFind(taxon); // (1)

    this.tester.documentName("queries")
      .operationName("FindTaxon")
      .variable("taxonId", savedTaxon.getId())
      .execute()
      .path("findTaxon.authorship")
      .entity(String.class)
      .isEqualTo("Me");
  1. testEntityManager 成功返回一個 ID。

詢問

query FindTaxon($taxonId: ID!) {
    findTaxon(id: $taxonId) {
        authorship
    }
}

Controller

@Controller
@AllArgsConstructor
public class BackboneTreeController {

  private final TaxonService taxonService;

  @QueryMapping
  public Taxon findTaxon(@Argument Integer id) {
    Optional<Taxon> taxon = taxonService.findTaxon(id);
    return taxon.orElse(null);
  }

}

服務

@Service
@AllArgsConstructor
public class TaxonService {

  private final TaxonRepository taxonRepository;

  public Optional<Taxon> findTaxon(Integer id) {
    return taxonRepository.findById(id); // (2)
  }
}
  1. 這是我希望回購協議返回實體的地方,但事實並非如此。 同樣在這里使用.findAll返回一個空列表。

資料庫

@Repository
public interface TaxonRepository extends JpaRepository<Taxon, Integer> {
}

請注意,當我運行應用程序並手動發送完全相同的查詢時,一切正常!

我不知道HttpGraphQlTester但我假設它生成請求,然后在單獨的線程中處理。

該線程不會看到測試中所做的更改,因為它們尚未提交。

如果這是原因,請通過將設置放在它自己的事務中來解決它,例如使用TransactionTemplate

暫無
暫無

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

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