create a Java micronaut app and add dependencies:
compile "io.micronaut:validation"
compile "io.micronaut.configuration:hibernate-validator"
Create a Controller:
package example;
import io.micronaut.http.HttpResponse;
import io.micronaut.http.annotation.Body;
import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Post;
@Controller("/mail")
public class EmailController {
@Post("/send")
HttpResponse index(@Body Email email) {
return HttpResponse.ok();
}
}
Create a POJO:
package example;
import io.micronaut.validation.Validated;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
@Validated
public class Email {
@NotNull
@NotBlank
String subject;
@NotNull
@NotBlank
String recipient;
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getRecipient() {
return recipient;
}
public void setRecipient(String recipient) {
this.recipient = recipient;
}
}
Write a test:
```package example
import io.micronaut.context.ApplicationContext;
import io.micronaut.http.HttpRequest;
import io.micronaut.http.client.RxHttpClient;
import io.micronaut.http.client.exceptions.HttpClientResponseException;
import io.micronaut.runtime.server.EmbeddedServer;
import spock.lang.AutoCleanup;
import spock.lang.Shared;
import spock.lang.Specification
class EmailControllerSpec extends Specification {
@Shared
@AutoCleanup
EmbeddedServer embeddedServer = ApplicationContext.run(EmbeddedServer, [
'spec.name': 'mailcontroller',
], 'test')
@Shared
@AutoCleanup
RxHttpClient client = embeddedServer.applicationContext.createBean(RxHttpClient, embeddedServer.getURL())
def "/mail/send cannot be invoked without subject"() {
given:
Email cmd = new Email(recipient: '[email protected]')
HttpRequest request = HttpRequest.POST('/mail/send', cmd)
when:
client.toBlocking().exchange(request)
then:
HttpClientResponseException e = thrown(HttpClientResponseException)
e.status.code == 400
}
}
Since it is a Spock test you will need to add these dependencies:
testCompile "org.codehaus.groovy:groovy-all:2.4.15"
testCompile "org.spockframework:spock-core:1.1-groovy-2.4"
```
Test should pass
Test fails
Find attached a sample project.
validate-in-controller.zip
You need @Body @Valid Email email in the controller action and the controller should be annotated with @Validated
I am going to reopen the issue and assign it to me to document this behaviour.
Most helpful comment
You need
@Body @Valid Email emailin the controller action and the controller should be annotated with@Validated