簡體   English   中英

如何使用 JUnit 和 Mockito 返回用於單元測試的數組?

[英]How to return an array for unit testing with JUnit and Mockito?

我正在測試一個將停止的應用程序,除非它可以將String拆分為String[] 我正在使用 JUnit 和 Mockito 來測試應用程序。 我設置了一個默認值和模擬行為如下。

String[] exampleStringList = {"exampleElement", "exampleElement"}; when(example.Call()).thenReturn(exampleStringList);

這會產生錯誤java: no suitable method found for thenReturn(java.Util.String[]) 我試圖通過用List<String>替換String[]然后添加必要的元素來解決這個問題。 這產生了與上述相同的錯誤。

TL;博士; 為了測試目的,我需要使用 JUnit 返回帶有元素的String[] ,但 thenReturn 不兼容。 如何使用 JUnit 和 Mockito 將String[]數組返回給測試?

我試圖重新創建你的場景,

  1. 服務定義

    public interface ExampleService { boolean doSomething();

    }

  2. 執行

    @Service @RequiredArgsConstructor public class ExampleServiceImpl implements ExampleService { private final ExampleDependantService exampleDependantService; @Override public boolean doSomething() { String[] strings = exampleDependantService.call(); if(strings.length >0){ return true; }else{ return false; } } }
  3. 依賴

     @Component public class ExampleDependantService { public String[] call(){ return new String[]{"exampleElement", "exampleElement"}; } }

4.測試

       @ExtendWith(SpringExtension.class)
       class ExampleDependantServiceImplTest {
       @Mock
       private ExampleDependantService exampleDependantService;
       @InjectMocks
       private ExampleServiceImpl exampleServiceImpl;

      @Test
      void doSomething_WhenCalled() {
      String[] exampleStringList = {"exampleElement", "exampleElement"};
      when(exampleDependantService.call()).thenReturn(exampleStringList);
      boolean b = exampleServiceImpl.doSomething();
       Assert.assertTrue(b);
      }
      }

5.Output

在此處輸入圖像描述

暫無
暫無

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

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