gpt4 book ai didi

java - 如何在@PostConstruct之前调用@BeforeMethod block

转载 作者:行者123 更新时间:2023-12-02 09:54:25 25 4
gpt4 key购买 nike

我正在下面编写 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.

您的问题的解决方案 -

  1. 正如 @chrylis 上面评论的那样,重构您的 SurveyPublisher 以使用构造函数注入(inject)来注入(inject)速率限制器。这样您就可以轻松进行测试。
  2. 注入(inject)导致问题的 Mock/Spy bean
  3. 创建测试配置,为您提供用作@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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com