我有2个测试文件,但每当我尝试运行gradle clean build时,
如果出现 java.lang.非法状态异常:无法载入ApplicationContext,当我移除 @AutoConfigureMockMvc 时,会收到错误 * 无法自动连接。找不到'MockMvc'类型的Bean。*
第一个文件作业测试
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class JobTest {
@Autowired
private WebApplicationContext applicationContext;
@Autowired
private MockMvc mockMvc;
@MockBean
private JobService jobService;
private static final String URI = "/testJob/";
@BeforeEach
void setup() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(applicationContext).build();
}
private final UUID jobId = UUID.fromString("d35089c0-8ca8-4a9d-8932-8464e9a0736c");
@Test
public void testRequestJob() throws Exception {
//create a request object
RequestBuilder requestBuilder = MockMvcRequestBuilders.post(URI)
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.ALL)
.content("testRequestString");
when(jobService.neededJob(anyString()).thenReturn(mockJob);
ResultActions perform = mockMvc.perform(requestBuilder);
assertEquals(HttpStatus.OK.value(), perform.andReturn().getResponse().getStatus());
//perform the request and get the response
perform.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$.data.jobId").exists());
}
}
第二个文件雇主测试
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class ShiftControllerTest {
@Autowired
private WebApplicationContext applicationContext;
@Autowired
private MockMvc mockMvc;
@MockBean
private EmployerService employerService;
@BeforeEach
void setup() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(applicationContext).build();
}
private final UUID jobId = UUID.fromString("d35089c0-8ca8-4a9d-8932-8464e9a0736c");
private static final String URI = "/employer/";
@Test
public void testEmployer() throws Exception {
RequestBuilder requestBuilder = MockMvcRequestBuilders.get(URI + jobId)
.accept(MediaType.ALL);
when(employerService.getEmployer(jobId)).thenReturn(mockEmployer);
ResultActions perform = mockMvc.perform(requestBuilder);
assertEquals(HttpStatus.OK.value(), perform.andReturn().getResponse().getStatus());
}
}
如果我注解一个文件,然后尝试运行gradle clean build它工作正常,任何建议将不胜感激。
1条答案
按热度按时间zbsbpyhn1#
在您发布的代码中,除了创建一个
MockMvc
对象(您已经通过@Autowired
注解创建了MockMvc
对象)之外,似乎没有将WebApplicationContext
用于其他任何用途。如果您不需要它用于其他任何用途,请尝试删除WebApplicationContext
。例如: