预期进一步的请求留下1个未满足的期望。已执行0个请求

时间:2018-12-24 12:48:06

标签: java spring rest testing

我的弹簧集成应用程序具有以下测试类。

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath*:/test-dao-rest.xml"})
public class TestEmployeeRestDao {

  @Autowired
  private EmployeeDao employeeRestDao;

  @Autowired
  private RestTemplate mockRestTemplate;

  private MockRestServiceServer mockServer;

  /**
   * Sets up.
   */
  @Before
  public void setUp() {
    mockServer = MockRestServiceServer.bindTo(mockRestTemplate).build();
  }

  @Test
  public void testGetEmployeeById() {
    when(mockRestTemplate.getForObject(url + 1, Employee.class)).thenReturn(emp2);
    mockServer.expect(times(1), requestTo(url + 1))
        .andExpect(method(HttpMethod.GET))
    Employee employee = employeeRestDao.getEmployeeById(1L);
    assertNotNull(employee);
    mockServer.verify();
  }

`}

我的xml配置

  <bean class="com.nikolay.client.handler.CustomResponseErrorHandler"
    id="customResponseErrorHandler"/>

  <bean class="org.mockito.Mockito" factory-method="mock" id="mockRestTemplate">
    <constructor-arg value="org.springframework.web.client.RestTemplate"/>
    <property name="messageConverters">
      <list>
        <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
      </list>
    </property>
    <property name="errorHandler" ref="customResponseErrorHandler"/>
  </bean>

  <bean class="com.nikolay.client.EmployeeRestDaoImpl" id="employeeRestDao">
    <property name="restTemplate" ref="mockRestTemplate"/>
  </bean>

</beans>

运行测试时,将引发错误。谁能说错什么呢?我不明白为什么会发生此错误。

java.lang.AssertionError: Further request(s) expected leaving 1 unsatisfied expectation(s).
0 request(s) executed.

您能帮我看看如何解决此问题。

1 个答案:

答案 0 :(得分:1)

mockRestTemplate在这里自动接线。这不是一个模拟。请勿在其上使用when(<>>).thenReturn(<<>>)

如果模板是bean,请用@MockBean而不是@Autowired进行注释。