簡體   English   中英

使用 Junit 和 Mockito 在方法內創建對象的測試方法

[英]Testing Methods that create objects inside the method with Junit and Mockito

您好,我對使用 Junit 和 Mockito 進行單元測試還比較陌生。 我認為我對這些原則有相當合理的理解,但我似乎無法找到任何解釋我具體嘗試在線測試的內容。

我想測試一個方法,它調用其他幾個方法(void 和 non-void),它也實例化方法體中的對象。 不幸的是,我不能分享代碼,因為它不是我的,但這是一個通用格式:

class classToTest {
     private final field_1;

     public void methodToTest( string id, List object_1, List object_2) {
          try {
               Map<SomeObject_1, SomeObject_2> sampleMap = new HashMap<>();
               method_1(object_1, object_2); //void function modifies object_2
               field_1.method_2(id, object_2);
               Map<SomObeject_1, List<object>> groupedList = groupList(object_2)
               //Then some stuff is added to the sampleMap
          }
          //catch would be here
}

目前我只關心測試method_1,我不能直接測試,因為它是一個私有方法,所以我必須通過這個父方法調用go。 我希望我可以更改代碼,但我被要求保持不變,並使用 Mockito 和 Junit 以這種方式進行測試。

我知道我需要模擬 class 的 object 來測試及其參數:

private classToTest classToTestObject;
@Mock private field_1 f1;

@Before
public void setup() {
     MockitoAnnotations.init.Mocks(this);
     classToTestObject = mock(classToTest.class, CALLS_REAL_METHODS);
}

但我不知道從哪里開始我的實際測試,因為我基本上可以只執行一個方法調用並忽略所有 rest。 我不能只是不忽略其他對象和方法調用,因為如果處理不當,主要方法將引發異常。

非常感謝任何幫助和指導,很抱歉我無法分享代碼。 謝謝你!

目前我只關心測試method_1,我不能直接測試,因為它是一個私有方法,所以我必須通過這個父方法調用go。

根據您的評論和代碼中的注釋:

method_1(object_1, object_2); //void function modifies object_2

您將設置一個測試,允許您驗證 object_2 的預期最終object_2 您可以使用 class 的真實實例來執行此操作,而不是模擬。

@Test
public void method1Test() {
    // Assemble - your preconditions
    ClassToTest subject = new ClassToTest();
    List<SomeType> object_1 = new ArrayList();
    List<SomeOtherType> object_2 = new ArrayList();

    // Populate object_1 and object_2 with data to use as input
    // that won't throw exceptions. Call any methods on subject that put
    // it in the desired state

    // Act - call the method that calls the method under test
    subject.methodToTest("some id that makes the method run correctly", object_1, object_2);

    // Assert - one or more assertions against the expected final state of object_2
    assertThat(object_2).matchesYourExpectations();
}

暫無
暫無

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

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