【发布时间】:2017-07-17 15:50:12
【问题描述】:
我正在尝试使用 JUnit、Mockito、Spring 测试和 Spring Security 测试来测试 spring rest 控制器类。以下是我正在执行测试的休息控制器类;
@RestController
public class EmployeeRestController {
@Autowired
private EmployeeService employeeService;
@PreAuthorize("hasAnyRole('ROLE_EMPSUPEADM')")
@RequestMapping(value = "/fetch-timezones", method = RequestMethod.GET)
public ResponseEntity<List<ResponseModel>> fetchTimeZones() {
List<ResponseModel> timezones = employeeService.fetchTimeZones();
return new ResponseEntity<>(timezones, HttpStatus.OK);
}
}
以下是我的测试类;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {SpringConfiguration.class})
@WebAppConfiguration
public class EmployeeRestControllerUnitTest {
private MockMvc mockMvc;
@Autowired
private WebApplicationContext webApplicationContext;
@Mock
private EmployeeService employeeService;
@InjectMocks
private EmployeeRestController employeeRestController;
@Before
public void init() {
MockitoAnnotations.initMocks(this);
Mockito.reset(employeeService);
mockMvc = MockMvcBuilders
.webAppContextSetup(webApplicationContext)
.build();
}
@Test
@WithMockUser(roles = {"EMPSUPEADM"})
public void testFetchTimezones() {
try {
mockMvc.perform(get("/fetch-timezones"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(jsonPath("$", hasSize(4)));
verify(emploeeService, times(1)).fetchTimeZones();
verifyNoMoreInteractions(employeeService);
} catch (Exception e) {
e.printStackTrace();
}
}
}
我参考了很多教程制作了上面的测试类。问题是我无法清楚地理解一切。所以,我有以下疑问。
-
我正在创建一个 EmployeeService 的模拟并使用 @InjectMocks 将其注入 EmployeeRestController,那么为什么会出现以下故障;
Wanted but not invoked: careGroupService.fetchTimeZones(); -> at com.example.api.test .restcontroller.EmployeeRestControllerUnitTest .testFetchTimezones(EmployeeRestControllerUnitTest.java:73) Actually, there were zero interactions with this mock. MockMvcBuilders.webAppContextSetup(webApplicationContext).build();工作正常。
我知道 MockMvcBuilders.standaloneSetup(employeeRestController) 用于测试单个控制器类,并且此方法无法使用 spring 配置。我们如何为这种方法提供弹簧配置,是否可能。
最后,这段代码是怎么做的:Mockito.reset(employeeService);有效。
【问题讨论】:
标签: spring-mvc junit mockito spring-test spring-restcontroller