我正在使用resttemplate来调用其他休息服务。并为此编写junit。在运行它时返回null表示它没有使用模拟实现
@RunWith(SpringJUnit4ClassRunner.class)
public class OrganizationEmployeeServiceTest {
@Mock
private RestTemplate restTemplate;
@InjectMocks
private OrganizationEmployeeServiceImpl organizationEmployeeService;
private MockRestServiceServer mockServer;
@Before
public void setUp() {
mockServer = MockRestServiceServer.createServer(restTemplate);
}
@After
public void tearDown() {
restTemplate = null;
organizationEmployeeService = null;
}
@Test
public void testMockCreation() {
assertNotNull(restTemplate);
}
@Test
public void testGetEmployeesByOrganizationId() throws JsonProcessingException {
List<Employee> testEmployees = new ArrayList<Employee>();
Employee employee1 = new Employee();
employee1.setEmployeeId(11);
employee1.setName("malav1");
employee1.setCity("bangalore1");
employee1.setOrganizationId(29);
testEmployees.add(employee1);
Employee employee2 = new Employee();
employee1.setEmployeeId(12);
employee1.setName("malav2");
employee1.setCity("bangalore2");
employee1.setOrganizationId(29);
testEmployees.add(employee2);
ObjectMapper objectMapper = new ObjectMapper();
String result = objectMapper.writeValueAsString(testEmployees);
mockServer.expect(requestTo("http://localhost:8080/springjpacontroller/employees/29")).andExpect(method(HttpMethod.GET))
.andRespond(withSuccess(result, MediaType.APPLICATION_JSON));
List<Employee> resultEmployees = organizationEmployeeService.getEmployeesByOrganizationId(29);
assertNotNull(resultEmployees);
mockServer.verify();
}
}
服务类方法:
@Autowired
RestTemplate restTemplate;
public void setRestTemplate(RestTemplate restTemplate){
this.restTemplate = restTemplate;
}
@Override
public List<Employee> getEmployeesByOrganizationId(int organizationId) {
Employee[] employees = restTemplate.getForObject(
"http://localhost:8080/"+ EMPLOYEE_SERVICE_ENDPOINT + organizationId, Employee[].class);
return Arrays.asList(employees);
}
这里运行junit时它给出了断言错误,因为这个雇员结果为空。