lundi 10 août 2020

Percisely configure spring junit 5 test config

Struggling for quite some with writing unit tests with spring-boot and junit5. I've read lots of articles and some of the junit5 documentation but didn't find anything that would help (or I'm just blind).

test:

@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 (it's an experiment to get only certain only certain classes but I failed):

@Configuration
@ComponentScan(basePackages = "com.some.path.to.rest")
class ScoreTestConfiguration {

}

While test execution , I assume, that global context is been initiated despite that I specified to load only part of it in @Configuration class.

My question how can I control and setup precise configuration of test context for spring-boot and junit5 test.

Actually if somebody will give some references about best practices hot to organize local testing framework I'll be really grateful. Thank you in advance!

Aucun commentaire:

Enregistrer un commentaire