簡體   English   中英

Mockito:模擬類始終調用真實方法

[英]Mockito: mocking class always calls real method

我想模擬一堂課。

該類的調用如下:

這是我的代碼:

@Mock
SomeClass someClass;

@InjectMocks
ToBeTested toBeTested;

@Before
public void setUp() {
    MockitoAnnotations.initMocks(this);
}

// in the test:
doReturn(returnValue).when(someClass).doSomething(param1, param2); 

我覺得我已經嘗試了@Mock@Spy以及doReturnwhen所有可能組合,但是不是doReturn方法調用,而是調用了真正的方法並拋出了NPE。

如何正確執行此操作?

如果需要,我將提供更多代碼。

編輯

SomeClassdoSomething()都是公共的,都不是最終的。

我嘗試使用MockitoJunitRunnerclass代替MockitoAnnotations ,但仍引發異常。

要測試的類:

@Component
public class ToBeTested implements Something {

    @Override
    public ReturnValue doSomeAction(Parameter theParam) {
        try {
            SomeClass theClass = new SomeClass();
            MyReturnValue myReturnValue = theClass.doSomething(
                    parameterOfTypeInputStream,
                    parameterOfTypeString
            );

        // other stuff

            return theParam;
        } catch (IOException e) {
            throw new RuntimeException("Oh no!");
        }
    }

// more

param1param2分別為InputStream和String類型。

當然,它不是模擬的,實際的代碼在doSomeAction方法中創建真實的類,以便將模擬注入SomeClass theClass應該是一個字段。

@Component
public class ToBeTested implements Something {
    SomeClass theClass;

    @Autowired
    public ToBeTested(SomeClass theClass) {
        this.theClass = theClass;
    }    

    @Override
    public ReturnValue doSomeAction(Parameter theParam) {
        try {
            MyReturnValue myReturnValue = theClass.doSomething(
                    parameterOfTypeInputStream,
                    parameterOfTypeString
            );

        // other stuff

            return theParam;
        } catch (IOException e) {
            throw new RuntimeException("Oh no!");
        }
    }

您的應用程序容器(Spring)應該創建bean SomeClass並將其注入,因為此構造函數由@Autowired注釋。

而且由於Mockito的@InjectMocks批注將查找構造函數,因此它將找到該構造函數並注入您在測試類( @Mock SomeClass someClass; )中聲明的模擬。

暫無
暫無

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

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