Spring Boot在测试时嘲笑其他休息客户端

问题描述 投票:1回答:1

我正在使用RestTemplate在我的Spring MVC项目中使用远程api。一个客户端用于名为LoginApiClient的身份验证,我必须在所有其他其他客户端中使用它。

这是我的休息客户端使用LoginApiClient并消耗QrCode Api。

@Service
public class QrKeyApiClient implements QrKeyApiClientBase {

  private RestTemplate restTemplate;

  @Autowired
  private LoginApiClientBase loginApiClient;

  public QrKeyApiClient(RestTemplateBuilder builder) {
    restTemplate = builder.build();
    restTemplate.setErrorHandler(new ErrorHandler());
  }

  //Other implementation details
}

这是LoginApiClient

@Service
public class LoginApiClient implements LoginApiClientBase {

    private RestTemplate restTemplate;

    public LoginApiClient(RestTemplateBuilder builder) {
        restTemplate = builder.build();
        restTemplate.setErrorHandler(new ErrorHandler());
    }

    //Other implementation details
}

我的QrKeyApiClient单元测试类如下所示。

@RunWith(SpringRunner.class)
@RestClientTest({QrKeyApiClient.class})
@Category(IUnitTest.class)
public class QrKeyApiClientTest {

  @Value("${getQrCodeUrl}")
  private String getQrCodeUrl;

  @Mock
  LoginApiClient loginApiClient;

  @Autowired
  private MockRestServiceServer server;

  @InjectMocks
  private QrKeyApiClient client;

  @Test
  public void getQrCodeAsImage_makesTrueCallToApi() throws Exception {
    ResponseEntity<String> responseEntity = mock(ResponseEntity.class);
    HttpEntity requestEntity = new HttpEntity<>(qrCodeGenerateRequest,new HttpHeaders());

    this.server
        .expect(requestTo(this.getQrCodeUrl))
        .andExpect(method(HttpMethod.POST))
        .andRespond(withSuccess("successResult", MediaType.TEXT_PLAIN));

    String qrImage = this.client.getQrCodeAsImage(qrCodeGenerateRequest);

    server.verify();

    assertThat(qrImage, is(notNullValue(String.class)));
  }
}

我不确定这是正确的方法,但我想在这个测试中模拟我的LoginApiClient并将其注入QrKeyApiClient。但我的测试没有传递错误,上面写着“创建名为'qrKeyApiClient'的bean的错误:通过字段'loginApiClient'表示不满意的依赖;”

那么我如何通过模拟其成员的其他客户端来测试这个客户端。

java spring unit-testing spring-boot
1个回答
1
投票

似乎问题是Spring和Mockito注释的混合使用。 Spring为应用程序上下文中的模拟服务提供了@MockBean注释。

尝试用@Mock@MockBean@InjectMocks替换@Autowired。可能不需要requestEntityresponseEntity

@RunWith(SpringRunner.class)
@RestClientTest({QrKeyApiClient.class})
@Category(IUnitTest.class)
public class QrKeyApiClientTest {

  @Value("${getQrCodeUrl}")
  private String getQrCodeUrl;

  @MockBean
  LoginApiClient loginApiClient;

  @Autowired
  private MockRestServiceServer server;

  @Autowired
  private QrKeyApiClient client;

  @Test
  public void getQrCodeAsImage_makesTrueCallToApi() throws Exception {    
    this.server
        .expect(requestTo(this.getQrCodeUrl))
        .andExpect(method(HttpMethod.POST))
        .andRespond(withSuccess("successResult", MediaType.TEXT_PLAIN));

    String qrImage = this.client.getQrCodeAsImage(qrCodeGenerateRequest);

    server.verify();

    assertThat(qrImage, is(notNullValue(String.class)));
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.