Java Mockito:mocking类总是调用real方法
我想模仿一门课 该类的名称如下: 这是我的密码:Java Mockito:mocking类总是调用real方法,java,unit-testing,mockito,Java,Unit Testing,Mockito,我想模仿一门课 该类的名称如下: 这是我的密码: @Mock SomeClass someClass; @InjectMocks ToBeTested toBeTested; @Before public void setUp() { MockitoAnnotations.initMocks(this); } // in the test: doReturn(returnValue).when(someClass).doSomething(param1, param2); 我觉
@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
和的所有可能组合,但不是模拟方法调用,而是调用真正的方法并抛出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,类应是一个字段
@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)应该创建beanSomeClass
,并在该构造函数由@Autowired
注释时将其注入
由于Mockito的@InjectMocks
注释将查找构造函数,它将找到此构造函数并注入您在测试类中声明的mock(@mock SomeClass SomeClass;
)。要测试的代码以及关于param1和param2的详细信息可能是goodIsSomeClass
最终版本?或剂量测量
?根据您拥有的Mockito版本的不同,可能无法存根final方法或final类中的方法。您是否在测试类中使用Mockito junit runner注释?您在
时是如何尝试的?问题是,代码是由其他人编写的,而某些类不是由Spring管理的(它没有@Component注释或任何内容)。在这里模拟SomeClass真的完全不可能吗?Mockito不应该注意到只有一个模拟被声明为construcor参数吗?Spring配置仍然可以在由@Bean
注释的某些方法中创建SomeClass
。尽管验证它可以共享,例如,它是线程安全的。Mockito将只注入在您的测试中使用eclared mock,这样您的测试就可以操纵mock实例。