None of these solutions helped here: Spring mockMvc doesn't consider validation in my test. Added all of these dependencies, nothing helps.
I use Spring Boot 2.1.2, pom.xml:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.2.RELEASE</version>
</parent>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-hateoas</artifactId>
</dependency>
<!-- Testing -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.github.springtestdbunit</groupId>
<artifactId>spring-test-dbunit</artifactId>
<version>1.3.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.dbunit</groupId>
<artifactId>dbunit</artifactId>
<version>2.5.4</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.jcabi</groupId>
<artifactId>jcabi-matchers</artifactId>
<version>1.3</version>
<scope>test</scope>
</dependency>
</dependencies>
I use standard hibernate validation '#NotNull':
#Entity
#Table(name="employee")
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonIgnoreProperties(ignoreUnknown = true)
public class Employee {
#Id
#Column
#GeneratedValue(strategy = GenerationType.IDENTITY)
protected Long id;
#NotNull(message = "Please provide name")
#Column(name = "name")
private String name;
#Column(name = "role")
private String role;
public Employee() {}
public Employee(String name, String role) {
this.name = name;
this.role = role;
}
}
#RestController
#RequestMapping(EmployeeController.PATH)
public class EmployeeController {
public final static String PATH = "/employees";
#Autowired
private EmployeeService service;
#PostMapping("")
public Employee newEmployee(#RequestBody #Valid Employee newEmployee) {
return service.save(newEmployee);
}
}
#Service
public class EmployeeService {
#Autowired
private EmployeeRepository repository;
public Employee save(Employee entity) {
return getRepository().save(entity);
}
}
#Repository
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
}
Then I test my controller:
#RunWith(SpringRunner.class)
#SpringBootTest
#Transactional
#DatabaseSetup("/employee.xml")
#TestExecutionListeners({
TransactionalTestExecutionListener.class,
DependencyInjectionTestExecutionListener.class,
DbUnitTestExecutionListener.class
})
public class EmployeeControllerWebApplicationTest {
#Autowired
private WebApplicationContext context;
private MockMvc mockMvc;
private static String employeeRouteWithParam = EmployeeController.PATH + "/{id}";
#Before
public void setup() {
mockMvc = MockMvcBuilders
.webAppContextSetup(context)
.build();
}
#Test
public void create_WithoutName_ShouldThrowException() throws Exception {
String role = "admin";
Employee expectedEmployee = new Employee(null, role);
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
String json = ow.writeValueAsString(expectedEmployee);
ResultActions resultActions = this.mockMvc.perform(post(PATH)
.contentType(MediaType.APPLICATION_JSON_UTF8)
.content(json))
.andDo(print());
String contentAsString = resultActions.andReturn().getResponse().getContentAsString();
System.out.println("content: " + contentAsString); // empty body
resultActions
.andExpect(status().isBadRequest())
.andExpect(jsonPath("error").exists()) // not exist!!!
.andExpect(jsonPath("timestamp").exists()); // not exist!!!
}
}
employee.xml:
<dataset>
<Employee id="1" name="John" role="admin"/>
<Employee id="2" name="Mike" role="user"/>
</dataset>
I can not understand why it does not work when I test through #MockMvc. What am i doing wrong? Status is correct, but there is no error content, empty response
But validation works if tested on a really running application, then everything works.
Related
I am newbie coder and I am trying to create a Spring boot API using MongoDB. This is the schema template of the database.
{
"id":"string",
"user_name":"string"
"product":[
{
"product_id":"string",
"prod_name":"string",
"price":"double",
"quantity":"number",
}],
"total":"double"
}
This is my entity class User.java
#Getter
#Setter
#NoArgsConstructor
#Document(collection="user")
public class User {
#Id
private String id;
#Indexed(unique=true)
private String user_name;
private Product product;
private double total;
}
This is another entity class Product.java
#Getter
#Setter
#Document(collection="product")
public class Product {
#Id
private String prod_id;
#Indexed(unique=true)
private String prod_name;
private double price;
private int quantity;
}
This is my UserRepository.java interface
#Repository
public interface UserRepository extends MongoRepository<User,String> {
}
This is my UserService.java interface
public interface UserService {
void saveUser(User user);
}
This is my UserServiceImpl.java class
#Service
public class UserServiceImpl implements UserService {
#Autowired
UserRepository userRepo;
#Override
public void saveUser(User user) {
userRepo.save(user);
}
}
This is my UserController.java class
#RestController
#RequestMapping("/usercart")
public class UserController {
#Autowired
private UserService userService;
#Autowired
private UserRepository userRepository;
#GetMapping("/")
public List<User> getCartInfo()
{
return userRepository.findAll();
}
#PostMapping("/order")
public ResponseEntity<?> add(#RequestBody User user)
{
userService.saveUser(user);
return new ResponseEntity<>(HttpStatus.OK);
}
}
This is my pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.demo</groupId>
<artifactId>cartDemo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>cartDemo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb-reactive</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>de.flapdoodle.embed</groupId>
<artifactId>de.flapdoodle.embed.mongo</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
This is my application.properties file
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=UserCart
When I try to use post method like
Body -
{ "id":"1222",
"user_name":"shivam",
"product":[{
"prod_id":"w121", "prod_name":"wheel",
"price":10,
"quantity":1 }],
"total":10 }.
My MongoDB object looks like - _id:ObjectId("e6789")
total :0, _class:"com.trial.spring.api.user.User"
I don't see your property file here, but most likely you are missing below properties in your application.properties file:
spring.data.mongodb.uri=mongodb://<username>:<pwd>#<host>/datatbase_name
I am using Spring Boot and the #NotNull is not working. When the name value is not provided the function runs fine.
#Entity
public class Employee implements Serializable{
#Id
//#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
//#Id
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
#NotNull // not working
private String name;
private String phone;
}
the controller is
#Controller
public class URLController {
#Autowired
EmployeeServiceImpl empService;
#GetMapping({"/", "/index"})
public String index1(Model model){
model.addAttribute("employee",new Employee());
return "index";
}
#PostMapping("/result")
public String result(#Valid #ModelAttribute Employee employee){
System.out.print(employee.getName());
empService.save(employee);
return "result";
}
}
pom.xml
http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
<groupId>com.springs</groupId>
<artifactId>springs</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>springs</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
i am using the model attribute to get the employee object. the pom.xml file contains the hibernate validator dependency.
you must add #Valid annotaion in mapping part in your code for example
void addEmployee(#Valid Employee emp);
using this import "import javax.validation.Valid;"
Another note if you want to validate List you must make a wrapper list
Like
public class ValidList<E> implements List<E> {
#Valid
private List<E> list;}
And override all methods in it
Try modifying method like below to check details about errors.
#PostMapping("/result")
public String result(#Valid #ModelAttribute("employee") Employee employee, BindingResult bindingResult){
List<FieldError> errors = bindingResult.getFieldErrors();
for (FieldError error : errors ) {
System.out.println (error.getObjectName() + " - " +error.getDefaultMessage());
}
System.out.print(employee.getName());
empService.save(employee);
return "result";
}
If no error in bindingResult then refer notnull-constraint-not-working to troubleshoot further.
I'm new on java world.I have this error "package org.springframework.boot does not exist" on my SpringApplication Runner class.But i added Spring Boot dependency to pom.xml
I do not understand why i got this error.
pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jersey</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>javax.transaction</groupId>
<artifactId>javax.transaction-api</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
UserDao
#Repository
public class UsersDao {
#PersistenceContext
private EntityManager entityManager;
public void save(Users users){
entityManager.persist(users);
}
}
UserDTO
public class UsersDto {
private Integer id;
private String name;
private String surname;
private String username;
private Boolean isSuperUser;
private String email;
private String password;
private Date created_at;
private Date updated_at;
public UsersDto(){
}
public UsersDto(Users users){
this.id = users.getId();
this.name = users.getName();
this.surname = users.getSurname();
this.email = users.getEmail();
this.isSuperUser = users.getSuperUser();
this.username = users.getUsername();
this.password = users.getPassword();
}//AND GETTER&SETTER
UserResources
#Component
#Path("/users")
public class UsersResources {
#Autowired
UsersService usersService;
#POST
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public Response saveCity(UsersDto usersDto){
Users users;
try{
users = usersService.saveUsers(usersDto);
}catch (Exception e){
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
return Response.ok(users).build();
}
}
And UserServices
#Service
public class UsersService {
#Autowired
private UsersDao usersDao;
#Transactional
public Users saveUsers(UsersDto usersDto){
Users users = new Users();
users.setName(usersDto.getName());
users.setEmail(usersDto.getEmail());
users.setSuperUser(usersDto.getSuperUser());
users.setSurname(usersDto.getSurname());
users.setPassword(usersDto.getPassword());
usersDao.save(users);
return users;
}
}
User model
#Entity
#Table(name="users")
public class Users implements Serializable {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="id")
private Integer id;
#Column(name="name")
private String name;
#Column(name="surname")
private String surname;
#Column(name="username")
private String username;
#Column(name="password")
private String password;
#Column(name="is_super_user")
private Boolean isSuperUser;
#Column(name="email")
private String email;
#Column(name="created_at")
private Date created_at;
#Column(name="updated_at")
private Date updated_at;
#PrePersist
protected void onCreate() {
created_at = new Date();
}
#PreUpdate
protected void onUpdate() {
updated_at = new Date();
}
Where is my fault?How can i fix it?And I want to ask similar question.Sometimes we got some errors but i can't find it.So we understand this error's reason is pom.xml dependency conflicts.But no error on maven.We are tired because of incompatible dependency.Has it any solution of prevent dependency conflicts?(like maven dependency validator)
For using spring boot a easier way it's to create a Spring Boot project using Spring Initiliazr https://start.spring.io/. You can create from here a maven project that has the Spring Boot or more other dependencies alredeay patched in.
If you are just starting why don't you generate the project using https://start.spring.io/.
You added core Spring dependencies but not a single Spring Boot dependency. You only have a Spring Boot BOM and parent which only manage dependencies with <dependencyManagement>. You can inspect your dependencies by running mvn dependency:tree.
If you use Intellij Idea, you can resolve this problem in such way
Right-click on the folder of your project.
Choose "Add framework support".
Find "Maven" and set the checkbox.
After that, Intellij starts to download all dependencies.
I am writing a web app with Spring Boot, Hibernate and PostgreSQL. I want to learn how to save things in DB, but now I can`t resolve my problem. I am getting an error caused by my controller by line:
silniaRepository.save(silniaDB);
error is just:
java.lang.NullPointerException
there is my pom:
<name>silnia</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF- 8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.mortbay.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>8.1.5.v20120716</version>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
part of my controller:
#Controller
public class SilniaController {
#Autowired
public SilniaService silniaService;
public SilniaRepository silniaRepository;
public SilniaDB silniaDB;
#RequestMapping("/db")
#ResponseBody
public String testMethod() {
StringBuilder response = new StringBuilder();
SilniaDB silniaDB = new SilniaDB()
.setNumber1(23);
silniaRepository.save(silniaDB);
for (SilniaDB i : silniaRepository.findAll()) {
response.append(i).append("<br>");
}
return response.toString();
}
my DB model:
#Entity
public class SilniaDB {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Column
private int number;
public int getNumber() {
return number;
}
public void setNumber (int number){this.number=number;}
public SilniaDB setNumber1(int number) {
this.number = number;
return this;
}
public SilniaDB withNumber(final int number) {
this.number = number;
return this;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#Override
public String toString() {
return "TaskEntity{" +
"id=" + id +
"number=" + number +
'}';
}
}
and typical repository interface:
#Repository
public interface SilniaRepository extends CrudRepository<SilniaDB, Long> {
public SilniaDB findByNumber(Integer number);
}
I really spent a lot of time on that issue. Thanks in advance for every comment or answer.
Your repository is simply not being injected.
You have to put #Autowired for each of the dependencies individauly.
#Autowired
private SilniaService silniaService;
#Autowired
private SilniaRepository silniaRepository;
also make those fields as private..
I want to use JPA in Spring boot with SQL Server by STS
This is my table:
MAVEN
<dependencies>
<dependency>
<groupId>com.hynnet</groupId>
<artifactId>sqljdbc-chs</artifactId>
<version>4.0.2206.100</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
application.properties
spring.datasource.driver-class- name=com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.datasource.url=jdbc:sqlserver://localhost:1433;databaseName=quanlybanhang
spring.datasource.username=sa
spring.datasource.password=1
spring.jpa.hibernate.ddl-auto=create
spring.datasource.initialize=true
spring.jpa.database=SQL_SERVER
Model.Account.class
#Entity
#Table(name="taikhoan",uniqueConstraints=#UniqueConstraint(columnNames = { "tendangnhap" }) )
public class Account {
#Id #GeneratedValue(strategy=GenerationType.AUTO)
private int id;
#NotNull
private String tendangnhap;
#NotNull
private String matkhau;
public Account(String tendangnhap, String matkhau) {
super();
this.tendangnhap = tendangnhap;
this.matkhau = matkhau;
}
public Account() {
super();
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTendangnhap() {
return tendangnhap;
}
public void setTendangnhap(String tendangnhap) {
this.tendangnhap = tendangnhap;
}
public String getMatkhau() {
return matkhau;
}
public void setMatkhau(String matkhau) {
this.matkhau = matkhau;
}
}
interface AccountDAO
public interface AccountDAO extends JpaRepository<Account, Integer>{
}
ServiceAccount.class
#Service
public class ServerAccount {
#Autowired
AccountDAO server;
public void them(Account acc){
server.save(acc);
}
public List<Account> lietke(){
return server.findAll();
}
}
ServicesAccount.class
#Service
public class ServerAccount {
#Autowired
AccountDAO server;
Account acc=new Account("khang", "1");
public void addAccount(){
server.save(acc);
}
public List<Account> lietke(){
return server.findAll();
}
}
I called method addAccount() in Controller and this is Exception I got
"java.lang.NoClassDefFoundError: org/springframework/orm/jpa/support/PersistenceAnnotationBeanPostProcessor"
"Caused by: java.lang.ClassNotFoundException: org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"
Please help me fix this exception. Thanks!!!
From your dependencies you missed (check you java version you use):
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<version>6.5.2.jre8-preview</version>
<scope>test</scope>
</dependency>
and into the application properties correct this line:
spring.datasource.driver-class- name=com.microsoft.sqlserver.jdbc.SQLServerDriver
to
spring.datasource.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.jpa.hibernate.dialect=org.hibernate.dialect.SQLServer2012Dialect