Spring Boot 如何在cubble场景中测试@valid

ctehm74n  于 2022-12-18  发布在  Spring
关注(0)|答案(1)|浏览(175)

给定以下类:

class Contact{
   @Getter
   @Setter
   @Email
   private String mail;
}
@RestController
class ContactController{
   @PostMapping(path = "/contacts")
    public ResponseEntity<Contact> addContact(
            @Valid @RequestBody Contact contact) {
     ....
    }
}

我如何在小 cucumber 场景中进行测试?
我尝试了以下方法:

Scenario Outline: validation failed use-case
    Given I am authenticated as "<userFirstName>"
    When I register a new contact "<contactJsonLocation>"
    Then it should throw an ConstraintViolationException of contact
    Examples:
      | userFirstName | contactJsonLocation                  | 
      | Simon         | contactWithMailNotWellFormatted.json |

步骤代码:

public CreateContactSteps(ContactController contactController) {
  When("^I register a new contact \"([^\"]*)\"$",
    (String contactJsonLocation) -> {
      try {
        Contact contact;
        String jsonContact = Files.readString(Paths.get(new ClassPathResource("files/" + contactJsonLocation).getURI()));   
        contact = objectMapper.readValue(jsonContact, Contact.class);
        String id = UUID.randomUUID().toString();
        contact.setId(id);
        createContactAttempt.setId(id);
        createContactAttempt.setMail(contact.getMail());
        contactController.addContact(contact);
      } catch (IOException e) {
        throw new RuntimeException(e);
      } catch (ConstraintViolationException e) {                                
        createContactAttempt.lastException = e;
       }
  });
  
  Then("^it should throw an ConstraintViolationException of contact$",
    () -> {
       Assertions.assertTrue(createContactAttempt.lastException instanceof ConstraintViolationException);
        createContactAttempt.lastException = null;
    });


当我在启动spring Boot 应用程序后测试创建新联系人时,验证部分一切正常,这意味着我收到了预期的400错误。但当我从测试上下文调用ContactController时,它无法验证,联系人被创建。我猜这与spring在幕后发挥了一些魔力有关。但是什么呢?现在我正在为自己创建这样的 cucumber 应用程序上下文(我可能做错了什么,我愿意接受建议/好的批评):

@RunWith(Cucumber.class)
@CucumberOptions(plugin = {"pretty", "html:FeaturesReport.html"},
        features = {"src/test/resources/features"})
public class AllAcceptanceTest {
}

@CucumberContextConfiguration
@ContextConfiguration(classes = {BeanConfiguration.class})
public class ContextConfigurationTesting implements En {
}

@Configuration
@RequiredArgsConstructor
public class ControllerConfiguration {
    @Bean
    public ContactController contactController() {
        return new ContactController(
                ... //every other bean the controller need 
        );
    }
    ...
}
1wnzp6jl

1wnzp6jl1#

@Valid注解signals the caller of addContact that the object should be valid。直接调用addContact可以绕过它。您可能需要考虑使用MockMvc来调用控制器。
我建议使用Sping Boot 来设置应用程序上下文。Spring Boot有一组丰富的特性,可以让您轻松地测试应用程序的许多方面。

相关问题