我想测试一些功能,一个服务的回购,是自动进入。我不想嘲笑自动测试,这更多的是一个集成测试的调试。
我的考试如下
@SpringBootConfiguration
@ExtendWith(SpringExtension.class)
@SpringBootTest
public class ThrottleRateServiceTest {
ThrottleRateService service = null;
@BeforeEach
public void setUp() {
service = new ThrottleRateServiceImpl();
}
@Test
public void testThrottoling() {
service.isAllowed("test");
}
}代码非常简单
@Service
public class ThrottleRateServiceImpl implements ThrottleRateService {
private final Logger logger = LogManager.getLogger(ThrottleRateServiceImpl.class);
@Autowired
ThrottleRateRepository throttleRateRepository;问题是throttleRateRepository总是空的。
我曾经尝试过测试这类代码。与Junit 4一起
@RunWith(SpringJUnit4ClassRunner.class) 把所有的豆子都弄干了。我已经有一段时间没有做过这样的集成测试了,Junit 5已经改变了,谢谢。
发布于 2021-11-27 22:49:13
该守则中的问题是:
@BeforeEach
public void setUp() {
service = new ThrottleRateServiceImpl();
}您不应该手动创建bean。在这种情况下,Spring无法管理它和自动存储库。
如果需要在每个方法调用之前重新创建服务,则可以使用类注释
@DirtiesContext(methodMode = MethodMode.AFTER_METHOD)。你可以读到更多关于它的这里。
与此不同的是,自动创建了类似于存储库的ThrottleRateServiceImpl。此外,对于正确的自动装配,您可能需要有一个测试配置。它可以是内部静态类,也可以是单独的类。
@SpringBootConfiguration
@ExtendWith(SpringExtension.class)
@SpringBootTest
public class ThrottleRateServiceTest {
@TestConfiguration
static class TestConfig {
@Bean
public ThrottleRateService throttleRateService() {
return new ThrottleRateServiceImpl();
}
}
@Autowired
ThrottleRateService service;
@Test
public void testThrottoling() {
service.isAllowed("test");
}
}您可以阅读有关在本教程中为测试和测试配置初始化bean的更多信息。
而且,非常有用的正式文件
如果您正在使用JUnit 4,请不要忘记在测试中添加@RunWith(SpringRunner.class),否则注释将被忽略。如果使用的是JUnit 5,则不需要将等效的@ExtendWith(SpringExtension.class)添加为@SpringBootTest和其他@…测试注释已经用它进行了注释。
发布于 2021-11-27 23:18:42
修正了,我所做的就是将@SpringBootTest替换为@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
并自动启动了ThrottleRateService
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class ThrottleRateServiceTest {
@Autowired
ThrottleRateService service;
@Test
public void testThrottoling() {
service.isAllowed("test");
}
}https://stackoverflow.com/questions/70138922
复制相似问题