Java 如何模仿春豆?

Java 如何模仿春豆?,java,spring,unit-testing,mockito,powermock,Java,Spring,Unit Testing,Mockito,Powermock,我试图模拟一个使用JAXR的类,这个类是spring组件 @Component public class PostmanClient { private WebTarget target; public PostmanClient() { Client client = ClientBuilder.newClient(); target = client.target(...); } public String send(String xml) {

我试图模拟一个使用JAXR的类,这个类是spring组件

@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创建的实例,而不是模拟实例。
如何避免这种行为并获得模拟实例

> P>如果使用Spring使用PrimeMcK,则应考虑以下提示:
1.使用@RunWith(SpringJunit4Runner.class)
2.使用@ContextConfiguration(“/test context.xml”)//在测试之前加载spring上下文
3.使用@PrepareForTest(..class)//模拟静态方法
4.使用
5.模拟Springbean最简单的方法是使用

回到你的问题上来

如果我没有理解错,您已经在spring上下文中定义了
postanclient
,这意味着您只需要使用
springockito
就可以实现您的目标,只需遵循springockito页面上的教程即可。

您可以使用BDD framework Spock为您的spring框架编写UT。使用SpockSpring扩展(Maven:groupId:org.spockframework,artifactId:SpockSpring),您可以在单元测试中加载Spring上下文

@WebAppConfiguration
@ContextConfiguration(classes = Application.class)
class MyServiceSpec extends Specification {
    @Autowired
    UserRepository userRepository
}
如果您有一些bean想要模拟它们,而不是从Spring上下文加载,那么可以在您想要模拟的bean上添加以下注释

@ReplaceWithMock

这是关于如何使用Spock为Spring应用程序编写UT的详细介绍。

我不确定您的实现有什么问题。也许PostmanClient应该是一个接口而不是类

然而,我在我的实践/测试项目中实现了一个类似的单元测试。也许这会有帮助:


在测试的构造函数中启动应用程序上下文之前,向注册模拟。原始bean将被一个mock替换,Spring将在任何地方使用mock,包括注入的字段。原始bean将永远不会被创建。

有一个选项可以使用纯Spring特性来伪造springbean。您需要为它使用
@Primary
@Profile
@ActiveProfiles
注释

我创建了一个示例来回答另一个问题,但也涵盖了您的案例。通过
SpringJUnit4ClassRunner
简单替换
MockitoJUnitRunner

简言之,我创建了JavaSpring配置,它只包括应该测试/模拟的类,并返回模拟对象而不是真正的对象,然后让Spring完成它的工作。非常简单和灵活的解决方案


从Spring Boot 1.4.x开始,它也适用于
MvcMock

您可以使用名为的新注释。

将模拟混合到集成测试中通常是个坏主意。不要使用
loadApplicationContext
通过Spring加载bean,或者使用其他配置文件为测试加载手动存根的PostmanClient。是的,但我不希望创建一个restful服务器来响应PostmanClient。另一种方法是使用模拟restful服务(如restito或模拟服务器)的框架。这个问题应该会让你知道怎么做。虽然我不建议这样做,特别是对于单元测试,但我不想使用SpringJunit4Runner,因为我需要在spring上下文加载之前使用DBUnit加载数据库上的数据集。我尝试使用SpringTestDBUnit,但框架侦听器总是在SpringContext侦听器之后执行。因此,我选择以编程方式加载数据集并创建应用程序上下文。这样做,我需要在上述所有操作之前创建模拟。@SandroSimas,您可以使用jUnit Spring规则。就像我的例子一样。但我怀疑您在集成测试中是否需要模拟对象,但您没有使用Spring