'MockMVC integration test - create User before Unit Test

I want to create Unit Tests for the class "ImageController". As an image must be owned by a created User, I want to create a User before the Unit tests are performed (with @Before). How do I create this User? In the testing of the UserController itself, I did it like:

this.mockMvc.perform(post("/users")
            .contentType(MediaType.APPLICATION_JSON)
            .content("{\"username\":\"username\",\"email\":\"email\", \"password\":\"password\" }"))


Solution 1:[1]

This depends on your application and the general test setup. If you have your repository mocked, just have the mock return a proper user. If you have an in-memory or containerized DB in the test, use whatever is available to you to add the user to that DB (e.g. call the real repository or your service class (whatever is called by your controller to create a user). Since this is really an integration test, you could also do the "create user" and "image" tests in one test case to make sure you have the user already created when you test the ImageController.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 EricSchaefer