亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在@PostConstruct之前調用@BeforeMethod塊

如何在@PostConstruct之前調用@BeforeMethod塊

嗶嗶one 2019-04-09 14:15:38
我正在編寫Spring Unit測試代碼。單元測試@Before方法沒有被執行。因為它直接運行@PostConstruct我得到了erorrs,Caused by: java.lang.IllegalArgumentException: rate must be positive因為默認值是0.00。我想設置一些值來請求最大限制,以便postcontstruct塊順利通過。我的代碼有什么問題?請幫忙。@Componentpublic class SurveyPublisher  {     @Autowired     private SurveyProperties surveyProperties;     @PostConstruct         public void init() {             rateLimiter = RateLimiter.create(psurveyProperties.getRequestMaxLimit());         }     }     public void publish() {         rateLimiter.acquire();         // do something     }}//單元測試類public class SurveyPublisherTest  extends AbstractTestNGSpringContextTests {     @Mock     SurveyProperties surveyProperties;     @BeforeMethod        public void init() {         Mockito.when(surveyProperties.getRequestMaxLimit()).thenReturn(40.00);     }     @Test     public void testPublish_noResponse() {         //do some test     }}
查看完整描述

2 回答

?
ITMISS

TA貢獻1871條經驗 獲得超8個贊

剛剛意識到它將始終postConstruct在Junit回調方法之前運行方法導致spring優先。如文件中所述 -

如果測試類中的方法使用@PostConstruct注釋,則該方法在基礎測試框架的任何before方法之前運行(例如,使用JUnit Jupiter的@BeforeEach注釋的方法),并且該方法適用于測試類中的每個測試方法。

解決方案問題 -

  1. 正如@chrylis在上面評論的那樣重構你SurveyPublisher使用構造函數注入來注入速率限制器。所以你可以輕松測試。

  2. 注入引起問題的Mock / Spy bean

  3. 創建測試配置以提供要用作的類的實例 @ContextConfiguration

    @Configurationpublic class YourTestConfig {
    
        @Bean
        FactoryBean getSurveyPublisher() {
            return new AbstractFactoryBean() {
                @Override
                public Class getObjectType() {
                    return SurveyPublisher.class;
                }
    
                @Override
                protected SurveyPublisher createInstance() {
                    return mock(SurveyPublisher.class);
                }
            };
        }}


查看完整回答
反對 回復 2019-05-15
  • 2 回答
  • 0 關注
  • 1787 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號