2017-06-05 16 views
2

我能夠建立併成功地與SpringBoot運行三個不同的測試配置1.5.3@Import VS @ContextConfiguration在單位進口豆測試

方法1#。使用@Import註釋導入Bean

@RunWith(SpringJUnit4ClassRunner.class) 
@Import({MyBean.class}) 
public class MyBeanTest() { 
    @Autowired 
    private MyBean myBean; 
} 

方法#2。利用@ContextConfiguration註釋

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(classes = {MyBean.class}) 
public class MyBeanTest() { 
    @Autowired 
    private MyBean myBean; 
} 

方法#3(使用內部類結構;基於the official blog post)的導入豆

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(loader=AnnotationConfigContextLoader.class) 
public class MyBeanTest() { 

    @Configuration 
    static class ContextConfiguration { 
     @Bean 
     public MyBean myBean() { 
      return new MyBean(); 
     } 
    } 

    @Autowired 
    private MyBean myBean; 

} 

考慮到@Import註釋文檔

表示一個或多個{@link Configuration @Configuration}類導入 。

和事實MyBean不是配置類,但一個bean類@Component註解,它看起來像方法#1註釋是不正確的。

@ContextConfiguration文檔

{@code @ContextConfiguration}定義了 用於確定如何加載和配置{@link org.springframework.context.ApplicationContext的ApplicationContext} 類級元數據進行集成測試。

聽起來像它更適用於單元測試,但仍應加載一種配置。

方法#1和#2更短更簡單。 方法#3看起來像一個正確的方法。

我對不對?還有其他的標準,爲什麼我應該使用方法#3,如表演或其他?

+0

'MyBean'是否依賴於其他bean?如果不是,我只會像'MyBean myBean = new MyBean();' –

+0

那樣實例化它,它取決於'org.springframework.core.env.Environment'。 – gumkins

回答

1

如果使用選項#3,實際上不需要指定加載程序。 From the doc 除了來自doc的示例外,您可以覆蓋env。與@TestPropertySource如果您需要在環境中注入屬性而不使用真實的屬性。

@RunWith(SpringRunner.class) 
// ApplicationContext will be loaded from the 
// static nested Config class 
@ContextConfiguration 
@TestPropertySource(properties = { "timezone = GMT", "port: 4242" }) 
public class OrderServiceTest { 

    @Configuration 
    static class Config { 

     // this bean will be injected into the OrderServiceTest class 
     @Bean 
     public OrderService orderService() { 
      OrderService orderService = new OrderServiceImpl(); 
      // set properties, etc. 
      return orderService; 
     } 
    } 

    @Autowired 
    private OrderService orderService; 

    @Test 
    public void testOrderService() { 
     // test the orderService 
    } 

}