【发布时间】:2019-05-13 05:49:59
【问题描述】:
我在下面写 Spring 单元测试代码。单元测试 @Before 方法没有被执行。由于它直接运行@PostConstruct,我收到错误Caused by: java.lang.IllegalArgumentException: rate must be positive,因为默认值为0.00。我想设置一些值来请求最大限制,以便 postcontstruct 块顺利通过。我的代码有什么问题?请帮忙。
@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
}
}
【问题讨论】:
-
你是如何从你的测试类运行测试方法的?我没有使用任何
@RunWith(MockitoJUnitRunner.class)。你确定你的模拟被注入了你正在测试的课程吗? -
我已经更新了测试类。它正在扩展
AbstractTestNGSpringContextTestsrun as TestNG Test 。 -
干净的答案是重写您的
SurveyPublisher以使用构造函数注入并注入速率限制器,这样您就可以轻松地在测试用例中测试它们。 -
在您的测试类中创建一个
static配置类。在其中创建一个@Bean方法,该方法返回您想要的SurveyProperties。您不需要为此进行模拟。或者根据您的测试,不要使用 Spring 并自己创建类和依赖项。
标签: java spring spring-test-mvc