我正在尝试模拟一个使用JAXRS的类,这个类是一个弹簧组件。
@Component
public class PostmanClient {
private WebTarget target;
public PostmanClient() {
Client client = ClientBuilder.newClient();
target = client.target(...);
}
public String send(String xml) {
Builder requestBuilder = target.request(MediaType.APPLICATION_XML_TYPE);
Response response = requestBuilder.post(Entity.entity(xml, MediaType.APPLICATION_XML_TYPE));
return response.readEntity(String.class);
}
}
这是我的测试方法:
@Test
public void processPendingRegistersWithAutomaticSyncJob() throws Exception {
PostmanClient postmanClient = mock(PostmanClient.class);
String response = "OK";
whenNew(PostmanClient.class).withNoArguments().thenReturn(postmanClient);
when(postmanClient.send("blablabla")).thenReturn(response);
loadApplicationContext(); // applicationContext = new ClassPathXmlApplicationContext("/test-context.xml");
}
当我调试postmanClient实例时,它是由Spring创建的实例,而不是模拟。 我怎样才能避免这种行为并获得模拟实例?
答案 0 :(得分:0)
如果您在Spring中使用PowerMock,则应考虑以下提示:
1.使用@RunWith(SpringJunit4Runner.class)
2.使用@ContextConfiguration(“/ test-context.xml”)//在测试前加载spring上下文
3.使用@PrepareForTest(.... class)//来模拟静态方法
4.使用PowerMockRule
5.模拟spring bean的最简单方法是使用springockito
回复你问题:
如果我不理解你的错误,你可以在spring上下文中定义PostmanClient
,这意味着你只需要使用springockito
来实现你的目标,只需按照springockito页面上的教程进行操作。
答案 1 :(得分:0)
您可以使用BDD框架Spock为您的Spring Framework编写UT。使用Spock Spring扩展(Maven:groupId:org.spockframework,artifactId:spock-spring),您可以在单元测试中加载Spring上下文。
@WebAppConfiguration
@ContextConfiguration(classes = Application.class)
class MyServiceSpec extends Specification {
@Autowired
UserRepository userRepository
}
如果你有一些bean想要模拟它们而不是从Spring上下文加载,你可以在你想要模拟的bean上添加以下注释。
@ReplaceWithMock
这个article详细介绍了如何使用Spock为你的Spring应用编写UT。
答案 2 :(得分:0)
我不确定您的实施有什么问题。也许PostmanClient应该是一个接口而不是类?
但是我在练习/测试项目中实施了类似的单元测试。也许它会有所帮助:
答案 3 :(得分:0)
在您的测试构造函数中启动应用程序上下文之前,使用Spring-ReInject注册模拟。原始的bean将被替换为mock,而mock将被Spring使用,包括注入的字段。原始bean永远不会被创建。
答案 4 :(得分:0)
可以选择使用简单的Spring功能来伪造Spring bean。您需要使用@Primary
,@Profile
和@ActiveProfiles
注释。
答案 5 :(得分:0)
我创建了example来回答另一个问题,但也涵盖了你的案例。通过MockitoJUnitRunner
简单替换SpringJUnit4ClassRunner
。
简而言之,我创建了Java Spring Configuration,其中只包含应该进行测试/模拟的类,并返回模拟对象而不是真正的对象,然后让Spring工作。非常简单灵活的解决方案。
它也适用于MvcMock
答案 6 :(得分:0)
从Spring Boot 1.4.x开始,您可以使用名为@MockBean的新注释。