首页 > 解决方案 > 通过邮递员调用时模拟第三方 api

问题描述

我有一个控制器类,它公开一个 Get API 并返回人员信息:

@RestController
public class PersonController {

@Autowired
PersonService personService;


@GetMapping
public Person getPersonInfo() {
    return personService.getPerson();
}
}

在 personService 中,我连接到第三方并从此 API 获取人员信息。现在我想使用邮递员在我的控制器中调用 getPersonInfo() API。我如何在这个场景中模拟第三方响应?我知道如果您使用测试(集成或单元)和线模,这是可能的。仅使用邮递员调用我的 API 怎么样?

标签: javaspring-bootrestmocking

解决方案


您可以使用@Profile注释

public interface PersonService {
...
}

@Service
@Profile("default")
public class PersonServiceImpl implements PersonService {
...
}

@Service
@Profile("mock")
public class MockPersonService implements PersonService {
...
}

如上定义,您可以选择带有 的配置文件appliation.properties。例如:

spring.profiles.active=mock

推荐阅读