【发布时间】:2020-08-10 14:43:18
【问题描述】:
使用 spring-boot 和 junit5 编写单元测试相当困难。 我已经阅读了很多文章和一些 junit5 文档,但没有找到任何有用的东西(或者我只是瞎了眼)。
测试:
@ExtendWith(SpringExtension.class)
@SpringBootTest(classes = ScoreTestConfiguration.class)
@AutoConfigureMockMvc
public class ScoreControllerTest {
private static final String SCORE_ENDPOINT = "/scoring";
private static final ObjectMapper MAPPER = new ObjectMapper();
@Autowired
private MockMvc mockMvc;
@MockBean
private ScoreService mockScoreService;
@BeforeEach
public void setUp() {
ScoreResponseDto response = getScoreResponseDto();
when(mockScoreService.getScore(any(),any(),any(),any(),any(),any())).thenReturn(response);
}
@NotNull
private ScoreResponseDto getScoreResponseDto() {
ScoreResponseDto response = new ScoreResponseDto();
response.setCid("qwe13423qw");
response.setData(new ScoreResponseDto.ScoringData(0.78f));
return response;
}
@Test
public void sendValidRequest_getResponse_andOkStatus() throws Exception {
String request = SCORE_ENDPOINT +
"/380715346789" + //msisdn
"?score_formula=1234" +
"&clientId=5678" +
"&cid=543" +
"&stateType=" + StateType.ACTIVE.name() +
"&subscriberType=" + SubscriberType.POSTPAID.getValue();
String jsonResponse = MAPPER.writeValueAsString(getScoreResponseDto());
System.out.println("jsonResponse: " + jsonResponse);
mockMvc.perform(get(request))
.andDo(print())
.andExpect(status().isOk())
.andExpect(content().string(jsonResponse));
}
}
配置(这是一个只获得某些特定类的实验,但我失败了):
@Configuration
@ComponentScan(basePackages = "com.some.path.to.rest")
class ScoreTestConfiguration {
}
在执行测试时,我假设全局上下文已启动,尽管我指定在 @Configuration 类中仅加载其中的一部分。
我的问题是如何控制和设置 spring-boot 和 junit5 测试的测试上下文的精确配置。
实际上,如果有人能提供一些关于组织本地测试框架的最佳实践的参考,我将不胜感激。 提前谢谢!
【问题讨论】:
-
放弃您的测试配置,因为这会破坏 Spring Boot 应用程序的正确初始化以进行测试。如果您的目标是仅测试控制器,请使用
@WebMvcTest而不是成熟的@SpringBootTest。 -
我已经开始使用这种方法并测试尝试加载完整的上下文
-
这就是
@SpringBootTest的全部意义,如果这不是您想要的,请不要使用@SpringBootTest。 -
如果目标是避免为控制器测试设置 Spring 上下文,您可能希望使用
MockMvcBuilders并准备一个独立的MockMvc。
标签: java spring-boot testing junit5