簡體   English   中英

測試有依賴關系的Spring Boot控制器? (JUNIT)

[英]Testing a spring boot controller which has dependencies? (jUnit)

我有這個測試課:

@RunWith(SpringRunner.class)
@WebMvcTest(ClassToBeTested.class)
public class ClassToBeTestedTests {

    @Autowired
    private MockMvc mockMvc;

    @Test
    public void simpleTestMethodToGetClassWorking(){
        Assert.assertTrue(true);
    }
}

但是在我要測試的課程中,我有這行:

@Autowired
AnnoyingServiceWhichIsADependency annoyingDependency;

因此,當我嘗試運行測試類時,出現此錯誤:

java.lang.IllegalStateException: Failed to load ApplicationContext

和逐行原因似乎拋出了這個:

Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'ClassToBeTested': Unsatisfied dependency expressed through field 'AnnoyingServiceWhichIsADependency'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type '<package-path>.AnnoyingServiceWhichIsADependency' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

我要補充的是,實際的類確實可以正常工作,並且可以完成它的本意,但是我在使它在單元測試領域中工作時遇到了麻煩。

所有幫助表示贊賞。

未為依賴關系類創建bean的原因是,您使用的是@WebMvcTest而不是@SpringBootTest :僅掃描控制器和MVC基礎結構類。 文檔

當測試僅針對Spring MVC組件時可以使用。

由於它是MVC測試,因此可以模擬服務依賴關系。 示例: https//reflectoring.io/spring-boot-web-controller-test/

您的測試應用程序上下文正在嘗試加載ClassToBeTested,但無法找到其依賴項之一,並通過該錯誤進行投訴。 基本上,您需要在測試上下文中具有該類型的@Bean。 一個選項是創建一個TestConfig類,該類通過@Bean批注提供該依賴項的Mock / Spy。 在測試中,您將必須通過@ContextConfiguration批注在剛才創建的測試配置中加載上下文。

https://docs.spring.io/spring/docs/current/spring-framework-reference/testing.html#spring-testing-annotation-contextconfiguration

@WebMvcTest僅用於掃描Web層-MVC基礎結構和@Controller類。 而已。 因此,如果您的控制器對其他Bean有某種依賴性,例如從您的服務層形成的其他Bean,則不會發現它們被注入。

如果要進行更全面的集成測試,請使用@SpringBootTest而不是@WebMvcTest

如果您想要更接近單元測試的內容,請模擬您的依賴關系。

還要注意,由於這些原因,不建議完全使用現場注入(@Autowired直接在現場)。 我建議您更改為構造函數注入(為Classtobetested添加一個構造函數,並在其上放置@Autowired批注。)然后對於單元測試,您可以傳遞一個模擬。 構造函數注入導致更可測試和可配置的設計。

只是嘲笑這種依賴性。 假設AnnoyingServiceWhichIsADependency是一個接口:

@RunWith(SpringRunner.class)
@WebMvcTest(ClassToBeTested.class)
public class ClassToBeTestedTests {

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private AnnoyingServiceWhichIsADependency annoyingDependency;

    @Test
    public void simpleTestMethodToGetClassWorking(){
        Assert.assertTrue(true);
    }
}

使用Mockito whenthenReturn方法來指導模擬。

暫無
暫無

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

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