mercredi 20 mars 2019

Spring Boot Testing with embedded Postgressql database

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.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();
    }
  }
}

Aucun commentaire:

Enregistrer un commentaire