簡體   English   中英

如何模擬春豆?

[英]How to mock a spring bean?

我正在嘗試模擬一個使用JAXRS的類,並且該類是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創建的一個實例,而不是模擬對象。 我如何避免這種行為並獲得模擬實例?

如果將PowerMock與Spring一起使用,則應考慮以下提示:
1.使用@RunWith(SpringJunit4Runner.class)
2.使用@ContextConfiguration(“ / test-context.xml”)//在測試之前加載spring上下文
3.使用@PrepareForTest(.... class)//模擬靜態方法
4.使用PowerMockRule
5.模擬彈簧豆的最簡單方法是使用springockito

回到您的問題
如果我不理解您的意思,您在spring上下文中定義了PostmanClient ,這意味着您只需要使用springockito來實現您的目標,只需按照springockito頁面上的教程進行操作即可。

您可以使用BDD框架Spock為您的Spring框架編寫UT。 使用Spock Spring擴展(Maven:groupId:org.spockframework,artifactId:spock-spring),您可以在單元測試中加載Spring上下文。

@WebAppConfiguration
@ContextConfiguration(classes = Application.class)
class MyServiceSpec extends Specification {
    @Autowired
    UserRepository userRepository
}

如果您有一些想要模擬它們而不是從Spring上下文加載的bean,可以在想要模擬的bean上添加以下注釋。

@ReplaceWithMock

本文詳細介紹了如何使用Spock為您的Spring應用程序編寫UT。

我不確定您的實現有什么問題。 也許PostmanClient應該是接口而不是類?

但是,我在練習/測試項目中實現了類似的單元測試。 也許會有所幫助:

https://github.com/oipat/poht/blob/683b401145d4a4c2bace49f356a5aa401fe81eb1/backend/src/test/java/org/tapiok/blogi/service/impl/PostServiceImplTest.java

在應用程序上下文在測試的構造函數中開始之前,向Spring-ReInject注冊您的模擬。 原始的bean將被一個模擬代替,Spring將在所有地方(包括注入的字段)使用該模擬。 原始的bean將永遠不會被創建。

有一個選項可以偽造僅具有純Spring功能的Spring bean。 您需要使用@Primary@Profile@ActiveProfiles注解吧。

我寫了一篇有關該主題的博客文章。

我創建了該示例以回答另一個問題,但同時也介紹了您的情況。 簡單的更換MockitoJUnitRunner通過SpringJUnit4ClassRunner

簡而言之,我創建了Java Spring Configuration,它僅包含應該測試/模擬的類,並返回模擬的對象而不是真正的對象,然后讓Spring起作用。 非常簡單靈活的解決方案。

它也可以與MvcMock一起MvcMock

從Spring Boot 1.4.x開始,您可以使用名為@MockBean的新注釋。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM