2017-10-12 53 views
0

我有以下我想測試的類。不得不測試一個匿名的內部類是非常困難的。任何幫助,將不勝感激。有沒有什麼方法可以用junit測試一個匿名的內部類?

@Configuration 
public class CustomErrorConfiguration { 

    @Bean 
    public ErrorAttributes errorAttributes() { 
     return new DefaultErrorAttributes() { 

      @Override 
      public Map<String, Object> getErrorAttributes(RequestAttributes requestAttributes, 
        boolean includeStackTrace) { 
       Map<String, Object> errorAttributes = super.getErrorAttributes(requestAttributes, includeStackTrace); 
       errorAttributes.remove("timestamp"); 
       errorAttributes.remove("status"); 
       errorAttributes.remove("exception"); 
       errorAttributes.remove("path"); 
       if (errorAttributes.containsKey("error") && errorAttributes.containsKey("message")) { 
        Map<String, Object> attr = new HashMap<>(); 
        attr.put("message", errorAttributes.get("message")); 
        return attr; 
       } 
       return errorAttributes; 
      } 

     }; 
    } 

} 
+4

爲什麼你不能在CustomErrorConfiguration裏面創建一個靜態類並測試它? – mlecz

回答

1

這應該是最低需要測試你的內部類:

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

@RunWith(SpringRunner.class) 
@ContextConfiguration 
public class BeanTest { 

    @Autowired 
    ErrorAttributes errorAttributes; 

    @Test 
    public void testMyBean() { 
     RequestAttributes requestAttributes = new RequestAttributes(); 
     System.out.println(errorAttributes.getErrorAttributes(requestAttributes, true)); 
    } 

    @Configuration 
    @ComponentScan(basePackages = "package.where.your.configuration.is") 
    public static class SpringTestConfig { 

    } 
} 

這個測試做了幾件事情:

  1. 它利用SpringRunner.class爲您創建一個ApplicationContext測試。
  2. @ContextConfiguration註解選取靜態嵌套類SpringTestConfig。這個類負責繁重的工作,並且實際掃描基本包,尋找其他標有Configuration,Bean,Component等的類。這會發現你的配置,從而導致Bean的實例化。
  3. 由於現在已經設置了應用程序上下文,我們可以像在普通應用程序代碼中那樣使用@Autowired注入bean。

我需要下面的maven依賴來完成這個(需要junit> = 4.12)。所有可用的maven中央:

<dependencies> 
     <dependency> 
      <groupId>org.springframework</groupId> 
      <artifactId>spring-core</artifactId> 
      <version>5.0.0.RELEASE</version> 
     </dependency> 
     <dependency> 
      <groupId>org.springframework</groupId> 
      <artifactId>spring-context</artifactId> 
      <version>5.0.0.RELEASE</version> 
     </dependency> 
     <dependency> 
      <groupId>org.springframework</groupId> 
      <artifactId>spring-test</artifactId> 
      <version>5.0.0.RELEASE</version> 
      <scope>test</scope> 
     </dependency> 
     <dependency> 
      <groupId>junit</groupId> 
      <artifactId>junit</artifactId> 
      <version>4.12</version> 
      <scope>test</scope> 
     </dependency> 
    </dependencies> 
相關問題