2017-02-20 8 views
0

次のコードは、Mvcコントローラ用のJUnitテストを書き込むための標準的なメソッドです。Spring Mvcコントローラをテストし、静的クラスを注入

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(classes = ApplicationTestCassandra.class) 
@WebAppConfiguration 
public class TestControllerTests { 

    @Autowired 
    private WebApplicationContext webApplicationContext; 

    private MockMvc mockMvc; 

    @Before 
    public void setup() throws Exception { 
     this.mockMvc = webAppContextSetup(webApplicationContext).build(); 
    } 

    @Test 
    public void testupTimeStart() throws Exception { 
     this.mockMvc.perform(get("/uptime")) 
       .andExpect(status().isOk()); 

    } 
} 

これはうまくいきますが、私はautowiredクラスをテストのための特別なクラスに置き換えたいと思います。私のコントローラにはCassandraSimpleConnectionクラスが@Autowiredを介して注入されています。 私はいくつかのアプローチを試みましたが、運はありません。 次のコードは、Mvc 404エラーのために失敗します。なぜなら、RESTインターフェイスでアプリケーションを実行していないと思うからです。

@RunWith(SpringJUnit4ClassRunner.class) 
//ApplicationTestCassandra is SpringBoot application startpoint class with @SpringBootApplication annotation 
//@ContextConfiguration(classes = ApplicationTestCassandra.class, loader = AnnotationConfigContextLoader.class) 
@ContextConfiguration(loader = AnnotationConfigWebContextLoader.class)//, classes = {ApplicationTestCassandra.class}) 
@WebAppConfiguration 
public class TestControllerTests { 

    @Service 
    @EnableWebMvc 
    @ComponentScan(basePackages={"blabla.functionalTests"}) 
    static class CassandraSimpleConnection { 

     public Metadata testConnection(TestConfiguration configuration) { 
      Metadata metadata = null; 
      // return metadata; 

      throw new RuntimeException("Could not connect to any server"); 
     } 
    } 

私は

@ContextConfiguration(loader = AnnotationConfigWebContextLoader.class, classes = {ApplicationTestCassandra.class}) 

CassandraSimpleConnectionは私の静的なクラスに置き換えされていない使用している場合。

誰かが私を助けてくれますか?注釈に関するドキュメントはかなり混乱しています。

+1

そして、なぜそれする必要があります。これは構成ではなく、決して検出されないサービスです。また、 '@ EnableWebMvc'と' @Configuration'クラスに '@ EnableWebMvc'と' @ ComponentScan'を追加するのはかなり役に立たないです。 –

+0

ありがとう、ありがとう。テストを実行するとき、サービスクラスをどのように置き換えることができますか? CassandraSimpleConnectionを模擬する最も簡単な方法は何ですか?私はむしろcom.datastax.driver.core.Clusterを嘲笑すべきですか? – Johannes

+0

CassandraSimpleConnectionに@Beanを使用して、テストケースでBeanを 'オーバーライド'できます –

答えて

0

のコメントを読んで、ここでのソリューションです:

@RunWith(SpringRunner.class) 
@SpringBootTest(classes = { MyApplication.class }) 
public class MyTests { 

     @MockBean 
     private MyBeanClass myTestBean; 

     @Before 
     public void setup() { 
      ... 
      when(myTestBean.doSomething()).thenReturn(someResult); 
     } 

     @Test 
     public void test() { 
      // MyBeanClass bean is replaced with myTestBean in the ApplicationContext here 
     } 
} 
関連する問題