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

标签 java spring spring-test-mvc

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

相关文章:

java - 将信用卡日期 MM/yy 格式化为 MM/dd/yyyy

java regex matcher.replaceAll 与组

java - Ubuntu 和 Windows 的奇怪 Eclipse/工作区行为

java - 如何修复 '' 查询单个对象时结果大小不正确 : expected 1, 实际 0' thouhj I' m ?

java - 如何在真实世界的 JMS 分布式架构中利用 Spring Integration?

java - Spring 批处理元素分割器

java - maven 无法从测试用例中找到任何包

spring-mvc - 如何对使用 thymeleaf 的安全 Controller 进行单元测试(不获取 TemplateProcessingException)?

spring - 在 Spring 3.2 上设置 JUnit 的 session 属性

spring - 如何使用 spring 的 MockRestServiceServer 模拟同一请求的多个响应?