簡體   English   中英

春天@ContextConfiguration

[英]Spring @ContextConfiguration

我正在運行下一個測試:

import static org.junit.Assert.assertEquals;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "/META-INF/spring/applicationContext.xml" })
public class FloorServiceTest {

    @Autowired
    private FloorService floorService;

    @Test
    public void testFloorService() {

        floorService.findById((long)1);

    }
}

與文件夾/APP/src/main/resources/META-INF/spring/下的文件applicationContext.xml

但似乎沒有正確自動裝配 bean:

  org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.confloorapp.services.FloorServiceTest': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.confloorapp.services.FloorService com.confloorapp.services.FloorServiceTest.floorService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.confloorapp.services.FloorService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

嘗試

@ContextConfiguration(locations = { "classpath:/META-INF/spring/applicationContext.xml" })

老實說,我會遠離 xml 並走這條路。 改變

@ContextConfiguration(locations = { "/META-INF/spring/applicationContext.xml" })

@ContextConfiguration(classes = { FloorServiceTestConfig.class })

並創建 about 類

@Configuration
public class FloorServiceTestConfig
{
    @Bean
    public FloorService floorService()
    {
          return new FloorService();
    }
}

這樣,當您需要為類模擬 bean 時,您無需測試它,如下所示

@Configuration
public class FloorServiceTestConfig
{
    @Bean
    public FloorService floorService()
    {
          return Mockito.mock(FloorService.class);
    }
}

上面給出的@Configuration的想法很好用。 但是為此,您必須使用@Configuration注釋您的類。 當涉及到離線測試時,即在您的組織中測試用例不在構建時執行時,這不是一個好主意。 在這種情況下,通過@ContextConfiguration(locations = { "classpath:/META-INF/spring/applicationContext.xml" })將是一個好主意。

要使用此方法,請注意以下事項:

  1. 檢查項目的.classpath文件中的類路徑。

  2. 如果你不能寫applicationContext相對於classpath的路徑。

您可以將另一個文件作為applicationContextTest文件夾保存在您的測試用例文件夾中,然后可以使用@ContextConfiguration(locations = { "classpath:applicationContextTest.xml"})

在您的情況下,您應該使用:

@ContextConfiguration(locations = "file:src/main/resources/META-INF/spring/applicationContext.xml")

另一個提示,我看到您在測試環境中使用了生產applicationContext.xml ,恕我直言,這不是一個好習慣,請嘗試使用特定的測試環境,例如applicationContext-test.xml ,這樣您就可以使用測試上下文而不會傷害您的生產環境。

暫無
暫無

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

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