[英]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
以及doReturn
和when
所有可能組合,但是不是doReturn
方法調用,而是調用了真正的方法並拋出了NPE。
如何正確執行此操作?
如果需要,我將提供更多代碼。
編輯
SomeClass
和doSomething()
都是公共的,都不是最終的。
我嘗試使用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
param1
和param2
分別為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.