Service object not mocked from controller testcase return empty object here is the below code
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Main.class)
@WebAppConfiguration
@ActiveProfiles(ApplicationConstants.DEVELOPMENT_PROFILE)
public class EmployeeControllerTest {
@Autowired
private WebApplicationContext webAppContext;
private MockMvc mockMvc;
@Mock
EmployeeCompositeService employeeCompositeService;
@InjectMocks
EmployeeController employeeController;
String name = "mike";
@Before
public void setUp() throws Exception {
mockMvc = MockMvcBuilders.webAppContextSetup(webAppContext).build();
MockitoAnnotations.initMocks(this);
}
@Test
public void testGetEmployees() throws Exception {
Mockito.when(employeeCompositeService.getEmployeesByName(name)).thenReturn(getEmployees());
String url = URIConstants.ROOT_CONTEXT + URIConstants.EMPLOYEE;
MvcResult result =
mockMvc.perform(post(url)
.contentType(APPLICATION_JSON_UTF8)
.content(convertObjectToJsonBytes(name))
.andExpect(status().isOk())
.andExpect(content().contentType(APPLICATION_JSON_UTF8))
.andExpect(jsonPath("$[0].employeeName").value("Mike"))
.andReturn();
String jsonContent = result.getResponse().getContentAsString();
LOGGER.debug("jsonContent: {}",jsonContent);
}
protected byte[] convertObjectToJsonBytes(Object object) throws IOException {
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
return mapper.writeValueAsBytes(object);
}
private List<Employee> getEmployees(){
//here is the logic to get List of employees to return. When the mockito call is invoked.
}
}
@RestController
@RequestMapping(value = URIConstants.ROOT_CONTEXT)
public EmployeeController{
@Autowired
private EmployeeCompositeService employeeCompositeService;
@RequestMapping(value=URIConstants.EMPLOYEE, method=RequestMethod.POST, consumes = INPUT_FORMAT, produces = OUTPUT_FORMAT)
public List<Employees> getEmployees(@RequestBody String name){
return employeeCompositeService.getEmployeesByName(name); //When invoke this method it calls inner service but not returns the mocked object.
}
}
我在 EmployeeController 中有一个服务调用,即
employeeCompositeService.getEmployees(String name)
所以我在 EmployeeControllerTestcase 中进行了 mock ,即
@Mock EmployeeCompositeService employeeCompositeService;
当我运行 Controller 测试用例时,它会调用进一步的服务调用和存储库并访问数据库
所以我不想调用内部服务从 Controller 返回此调用 employeeCompositeService.getEmployeesByName(name);
的结果。
您能告诉我上面的代码中我做错了什么吗?提前致谢
最佳答案
EmployeeCompositeService
模拟对象已创建,但未注入(inject)到任何地方。这是在测试中初始化一个类成员,但由于它没有被注入(inject)到 Controller 中,所以正在使用真正的、面向数据库的实现。要将模拟注入(inject)到 Controller 中,请在测试中将 Controller 声明为类成员,并使用 org.mockito.InjectMocks 注释对其进行注释。这将从带有 @Mock
注释的测试中获取类成员,并将它们注入(inject)到实现相同接口(interface)的 Controller 的字段中。
下一步是将 Controller 注入(inject)到 MockMvc
对象中,方法是将其指定为 mockMvc = MockMvcBuilders.standaloneSetup(employeeController).build()
。
关于java - 服务对象没有用数据模拟?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32842157/