简体   繁体   中英

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\" }"))

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 (eg 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM