我正在編寫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注釋的方法),并且該方法適用于測試類中的每個測試方法。
解決方案問題 -
正如@chrylis在上面評論的那樣重構你
SurveyPublisher
使用構造函數注入來注入速率限制器。所以你可以輕松測試。注入引起問題的Mock / Spy bean
創建測試配置以提供要用作的類的實例
@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); } }; }}
添加回答
舉報
0/150
提交
取消