我正在下面编写 Spring 单元测试代码。单元测试 @Before 方法没有被执行。由于它直接运行@PostConstruct,我收到错误 Caused by: java.lang.IllegalArgumentException: rates must be Positive
因为默认值为 0.00。我想设置一些值来请求最大限制,以便后构造 block 能够顺利通过。我的代码有什么问题?请帮忙。
@Component
public 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
}
}
最佳答案
刚刚意识到它总是会在 Junit 回调方法之前运行 postConstruct
方法,导致 spring 优先。正如文档中所解释的 -
if a method within a test class is annotated with @PostConstruct, that method runs before any before methods of the underlying test framework (for example, methods annotated with JUnit Jupiter’s @BeforeEach), and that applies for every test method in the test class.
您的问题的解决方案 -
- 正如 @chrylis 上面评论的那样,重构您的
SurveyPublisher
以使用构造函数注入(inject)来注入(inject)速率限制器。这样您就可以轻松进行测试。 - 注入(inject)导致问题的 Mock/Spy bean
创建测试配置,为您提供用作
@ContextConfiguration
的类实例@Configuration public class YourTestConfig { @Bean FactoryBean getSurveyPublisher() { return new AbstractFactoryBean() { @Override public Class getObjectType() { return SurveyPublisher.class; } @Override protected SurveyPublisher createInstance() { return mock(SurveyPublisher.class); } }; } }
关于java - 如何在@PostConstruct之前调用@BeforeMethod block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56106403/