MockRestServiceServer不会在测试中被调用

时间:2019-12-24 03:09:06

标签: spring-boot unit-testing spring-test

我创建了一些类来测试RestTemplate客户端。可以从Postman毫无问题地调用该服务。但是,当我使用MockRestServiceServer调用服务时,断言失败。该端点似乎没有被调用。

这是测试班

@RunWith(SpringRunner.class)
@ActiveProfiles("test")
@RestClientTest([ Config.class, UserService.class])
class UserServiceSpec  extends Specification{
 Logger LOG = LoggerFactory.getLogger(UserServiceSpec)

@Autowired
UserService service

@Autowired
MockRestServiceServer server;

@Autowired
ObjectMapper objectMapper;

def setup() {
    User user = createUser()
    String json = objectMapper.writeValueAsString(user)
    this.server.expect(requestTo("/user/{type}"))
            .andExpect(method(HttpMethod.POST))
            .andExpect(requestToUriTemplate("/user/{type}",Type.Business.name()))
            .andExpect(content().json(json, "UTF-8"))
            .andRespond(withSuccess(json, APPLICATION_JSON))
}
@Test
def "User creation should be successful"(){
    given:
    User user = createUser()
    when:
     User result = service.createUser(user, Type.Business)
    then:
    result!=null
}

static User createUser(){
    User user = new User()
    user.firstName = 'Cassie'
    user.class = Type.Business.name()
    user.lastName = 'Wayne'
    user.age = 39
    return user
 }
}

这是其他班级

@Configuration
class Config{

 @Bean(name = "userRestTemplate")
 public RestTemplate userRestTemplate(RestTemplateBuilder builder, 
 @Value("${user.service.client.uri}") String uri){
    RestTemplate restTemplate = builder.rootUri(uri)
            .setConnectTimeout(Duration.ofMillis(2000))
            .setReadTimeout(Duration.ofMillis(1000 * 60))
            .build();
    System.out.println("URI :: "+uri);
    return restTemplate;
   }
 }




 @Service
 public class UserService  {

 private Logger LOG = LoggerFactory.getLogger(UserService.class);
 @Autowired
 private RestTemplate userRestTemplate;

 public User createUser(User user, Type type){
    Map<String,String> uriVariables = new HashMap<>();
    uriVariables.put("type", type.name());
    HttpEntity<User> request = new HttpEntity<>(user);
    return userRestTemplate.postForObject("/user/{type}",request,User.class, uriVariables);
 }

}

application-test.properties

user.service.client.uri=http://localhost:8080

错误如下

java.lang.AssertionError:预期没有其他请求:HTTP POST用户/业务 0个请求已执行。

0 个答案:

没有答案