如何使用junit5测试控制器

hpcdzsge  于 2021-07-13  发布在  Java
关注(0)|答案(1)|浏览(385)

我有以下控制器:

@PostMapping(VALIDATE_CREDENTIALS)
public AuthenticationResponse validateCredentials(@PathVariable final String memberLoginName, @RequestBody UserCredential userCredential)
{
  log.info("validateCredentials:+ validating for memberLoginName={}", memberLoginName);

  UserCredentialDomain userCredentialDomain = credentialMapper.apply(userCredential, memberLoginName);

  AuthenticationResponseDomain authenticationResponse = credentialValidationPort.authenticate(userCredentialDomain);

  AuthenticationResponse convertedResponse = authenticationResponseMapper.apply(authenticationResponse);

  log.info("validateCredentials:- response={}", convertedResponse);
  return convertedResponse;
}

价值 VALIDATE_CREDENTIALS/validate/{username} .
我正在创建一个基本的控制器测试。只是嘲笑而已。

@WebMvcTest(controllers = {AuthenticateMemberController.class})
@AutoConfigureMockMvc(addFilters = false)
@ContextConfiguration(classes = {TestConfig.class})
@ExtendWith(MockitoExtension.class)
public class AuthenticateMemberControllerTest
{
@Mock
private CredentialValidationPort credentialValidationPort;

@Mock
private WebApplicationContext wac;

private MockMvc mockMvc;

@BeforeEach // For Junit5
public void setup() {
  mockMvc = MockMvcBuilders.standaloneSetup(wac).build();
}

@Test
public void shouldSuccessfullyValidateCredentials() throws Exception
{when(credentialValidationPort.authenticate(buildUserCredential())).thenReturn(buildAuthenticationResponseDomain());

  MvcResult resultActions = mockMvc.perform(post("http://localhost:8080/validate/bob")
                                               .contentType(MediaType.APPLICATION_JSON)
                                               .content("{\"password\":\"dfd\"}"))
                                   .andExpect(status().isOk())
                                   .andReturn();

  AuthenticationResponse response = getResultFromJson(resultActions);

  assertThat(response).as("The response from the controller")
                      .hasFieldOrPropertyWithValue("success", true);
}

private AuthenticationResponse getResultFromJson(MvcResult result) throws UnsupportedEncodingException, JsonProcessingException
{
  ObjectMapper mapper = new ObjectMapper();
  AuthenticationResponse response = mapper.readValue(result.getResponse().getContentAsString(), AuthenticationResponse.class);
  return response;
}

private AuthenticationResponseDomain buildAuthenticationResponseDomain()
{
  return AuthenticationResponseDomain.builder()
                                     .memberLoginName("bob")
                                     .memberId("123")
                                     .message("")
                                     .success(true)
                                     .build();
}

private UserCredentialDomain buildUserCredential()
{
  return UserCredentialDomain.builder()
                             .password("dfd")
                             .username("bob")
                             .build();
}
}

这是我的testconfig类:

@EnableAutoConfiguration
@Configuration
@ComponentScan(basePackages = "com.kool.exchange.controller")
public class TestConfig
{
@Bean
public CredentialMapper credentialMapper()
{
   return new CredentialMapper();
}

@Bean
public AuthenticationResponseMapper authenticationResponseMapper()
{
   return new AuthenticationResponseMapper();
}

@Bean
public CredentialValidationPort mockCredentialValidationPort()
{
   return Mockito.mock(CredentialValidationPort.class);
}
}

当应用程序运行时,我可以通过postman调用控制器,但是我得到Assert错误;预计200,但得到404。我想知道为什么我的测试不能启动控制器?我尝试了各种不同的网址,但没有运气。我使用的是jupiter junit 5,现在是spring 2.4.2。

7cwmlq89

7cwmlq891#

您假设测试后端侦听端口8080。然而,情况可能并非如此。您可以尝试在没有主机名和端口的情况下执行请求,也可以尝试在运行时标识端口,如下所述:spring:how to discover the http port at runtime

相关问题