簡體   English   中英

Mocking 新 object 方法在 Junit5 中調用

[英]Mocking new object method call in Junit5

我模擬了另一個 class 方法調用,它在生產中調用,如 new B().somemethod (arg) 它具有返回類型 void 和 newD().anymenthod() 它具有返回類型 inputstream

在測試方法中,我正在做 mocking 就像 donthing().when(b) 一樣。 某種方法();

When(d.anymehod()).thenreturn(inputstream);(這里是我提供的輸入流)

在這里我已經做了@Mock B b;

@Mock D d;

在這里,我的測試用例成功運行,但當時也調用了模擬方法。

在這里我不想改變生產代碼,只有測試用例實現可以改變。

''' java

class TestSystem{

@InjectMock
System sys;

@Mock 
B b;
@Mock
D d;

@BeforeEach
void setup(){
MockitoAnnotation.openMocks(this);
}

@Test
testModule(){
InputStrem input = null;
when(d.anymethod()).thenReturn(inputStrem);
doNothing().when(b).somemethod();
sys.module();

}
        

Class System{

public void module(){

    //some code .....
    
    new B().somemethod();
    
    inputStrem = new D().anymethod(value);
}



Class B{
public void somemethod(){
//some code .....
}    }


Class D{
public InputStrem anymethod(){
//some code ......

}    
}

'''

嘗試像這樣初始化 Mock:

  @InjectMocks
  private System sys;

  @Mock 
  B b;
  @Mock
  D d;

  private AutoCloseable closeable;

  @BeforeEach
  void init() {
    closeable = MockitoAnnotations.openMocks(this);

  }

  @AfterEach
  void closeService() throws Exception {
    closeable.close();

  }


  @Test
  testModule(){...}

暫無
暫無

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

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