If you have read the use of Junit to write unit tests , you will know that when writing unit tests for Controller, you will Mock the Service layer.
It looks like this:
But in addition to unit tests, you also need to write integration tests, which are requests that simulate the entire process.
The integration test also uses MockMvc, but if @WebMvcTest is added like the unit test, it is not very good, because the service code is not mocked, and an error will be reported.
This problem can be solved in two ways:
method one
Remove the @Autowired annotation and declare MockMvc manually.
MockMvc can be manually declared using MockMvcBuilders.webAppContextSetup in @Before.
@WebAppConfiguration
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserInfoControllerTest {
@Autowired
private WebApplicationContext webApplicationContext;
private MockMvc mockMvc;
@Before
public void setUp() {
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
// ... 省略
}
Method Two
Annotate with @AutoConfigureMockMvc so that MockMvc objects can be injected using @Autowired.
@WebAppConfiguration
@AutoConfigureMockMvc(addFilters = false)
@RunWith(SpringRunner.class)
@SpringBootTest
public class AccessRecordControllerTest {
@Autowired
private MockMvc mockMvc;
// ... 省略
}
Notice:
You need to add addFilters = false, otherwise it may cause the AntBuservice filter to go through, resulting in the need to log in, so the integration test fails
This article is published by mdnice Multiplatform
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。