I want to test my controller in Spring-Boot 2.1.3. I want to simulate a POST request. This works quite well but I can't save the data to my Postgres database because H2 can't do JSONB. Therefore I use this library to embed Postgres.
That works quiet well, the database starts but I can't/know how I can bring my mock to save the data in the embedded database.
Do you have any ideas ?
My Test:
@RunWith( SpringRunner.class )
@AutoConfigureMockMvc
@SpringBootTest
public class ControllerTest
{
@InjectMocks
private Student student;
@InjectMocks
private StudentInfo studentinfo;
@Autowired
private MockMvc mockMvc;
@ClassRule
public static PreparedDbRule preparedDbRule = EmbeddedPostgresRules.preparedDatabase( FlywayPreparer.forClasspathLocation( "db/migration" ) );
@Test
public void test() throws Exception
{
try(EmbeddedPostgres postgres = EmbeddedPostgres.builder.setPort(62239).start();
Connection connection = postgres.getPostgresDatabase().getConnection()){
String jsonString = "{"Student" : "name", "course" : "course1"}";
this.mockMvc.perform( post( "/students" )
.contentType( MediaType.APPLICATION_JSON )
.content( jsonString) )
.andDo( print() )
.andExpect( status().is( 201 )
);
}catch( Exception e){
e.printStackTrace();
}
}
}
My application.properties:
spring.datasource.driver-class-name=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql://localhost:62239/postgres
spring.datasource.username=postgres
spring.datasource.password=postgres
flyway.enabled=false
This is not a duplicate question from this, because in this question they used a libary to solve the problem which is only available/compatible in Spring-Boot 1.4.0
upports both Spring and Spring Boot frameworks Supported versions are Spring 4.3.0+ and Spring Boot 1.4.0+
Edit After some testing i found out that i should use an "application.properties" file for my Test. I also set the Port for the Database. But now my I get an random port although i set it with setPort(). I get an random port every start.