目前,我有一个项目使用TestNG对我的Spring项目执行测试。在我的项目中,我有一组虚拟接口,用于处理Eureka配置上的外部调用。在执行过程中,我很难理解如何在测试的基础上模拟/拦截这些调用。
下面是我的一个伪接口的例子:
@FeignClient ("http://my-service")
public interface MyServiceFeign {
@RequestMapping (value = "/endpoint/{key}", method = RequestMethod.GET)
SomePojo getByKey(@PathVariable ("key") String key);
}我有一个依赖于客户的服务:
@Service
public class MyService {
@Autowired
private MyServiceFeign theFeign;
public SomePojo doStuff() {
return theFeign.getByKey("SomeKey");
}
}我的测试是通过以下方式启动的:
@SpringBootTest (
classes = Service.class,
webEnvironment= SpringBootTest.WebEnvironment.RANDOM_PORT
)
@TestExecutionListeners (
inheritListeners = false,
listeners = {
DependencyInjectionTestExecutionListener.class,
TransactionalTestExecutionListener.class
}
)
@DirtiesContext
@ContextConfiguration (initializers = CustomYamlLoader.class)
@ActiveProfiles ("test")
publi class MyModuleTest extends AbstractTestNGSpringContextTests {
// ....
}我希望在我的测试中所做的是执行这样的操作:
@Test
public void doSomeTest() {
SomePojo fakeReturn = new SomePojo();
fakeReturn.setSomeStuff("some stuff");
/*
!!! do something with the injected feign for this test !!!
setupFeignReturn(feignIntercept, fakeReturn);
*/
SomePojo somePojo = injectedService.doStuff();
Assert.assertNotNull(somePojo, "How did I get NULL in a fake test?");
}所以,我的困境是:我缺少一个关键的理解来做到这一点,我想。我完全忽略了该如何处理这件事的概念。我不认为在这里使用回退实现是有意义的,但我可能错了。
帮助!
发布于 2017-02-27 21:25:28
据我所知,您处理的是冒充客户端(也可能是安全性最高的客户端,如basic或OAuth2),并希望进行测试。但是实际上,如果假冒伪劣客户端检索有效的结果,参加测试并不是为了测试MyServiceFeign是否工作,而是MyService工作正常。
为此,您不实际注入您的假装客户端,而是模拟 it。
简而言之,这可以通过两个步骤来实现:使用@MockBean而不是@Autowired,并在使用它之前描述客户端的行为。
@RunWith(SpringRunner.class)
@SpringBootTest(classes = YourApp.class)
public class MyServiceUnitTest {
@MockBean
private MyServiceFeign myFeignClient;
@Autowiered
private MyService myService;
@Test
public void testSync() {
given(myFeignClient.getByKey("SomeKey")).willReturn(
new SomePojo("SomeKey")
);
assertEquals("SomeKey", myService.doStuff().getKey());
}
}如前所述,spring使用莫基托来测试组件。我描述了带有oauth2截取的更高级设置和两种测试oauth2拦截假客户端的方法。
https://stackoverflow.com/questions/42306453
复制相似问题