I want test the method like this
@PostMapping(value = "/test")
public String test(@Valid TestModel model) {
return model.getUsername();
}
and the TestModel is this
@Getter
@Setter
public class TestModel {
private MultipartFile[] image1;
private MultipartFile[] image2;
private MultipartFile[] image3;
private String username;
private String password;
}
I can use httpclient to test this but I don't think this is a good idea,so any other methods with spring test?
When you test the Controllers, you are probably doing an integration testing. I write Spring MVC based test cases and with Spring boot, more power to
@AutoConfigureMockMvc
Reference: https://docs.spring.io/spring/docs/5.0.5.RELEASE/spring-framework-reference/testing.html#spring-mvc-test-framework
http://www.baeldung.com/spring-boot-testing
It goes something like this after configuration:
If, on the other hand you want to set a fast execution unit test without having to start SpringBoot alltogether... read on.
Using @SpringBootTest sets up a full integration testing environment which starts a full SpringBoot instance so it is relatively time consuming when actively developing. Spring MockMVC comes to the rescue as it emulates a servletContainer to a point where you can incorporate any request filtering or exception handling tests in your unit tests suite.
You can configure this setup with the following approach:
Configure a tailored test context: @ContextConfiguration allows you specify the classes you need for your test. Set Mockito MockMvc which moreless emulates a servlet container and set your tests fixture and dependencies.
Configure a mock MVC "servlet emulator": register handler beans in the context and build the mockMvc emulator (Note: there are two possible configuration: standaloneSetup or webAppContextSetup; refer to the documentation). The builder rightfully implements the Builder pattern so you can chain configuration commands for exception resolvers and handlers before calling build().
Run your tests
Hope this helps.
Jake.
It’s really easy with MockMvc. Also you can check your response with JsonPath. Spring MVC offers a standaloneSetup that supports testing relatively simple controllers, without the need of context.
Build a MockMvc by registering one or more @Controller's instances and configuring Spring MVC infrastructure programmatically. This allows full control over the instantiation and initialization of controllers, and their dependencies, similar to plain unit tests while also making it possible to test one controller at a time.
An example test for your controller can be something as simple as