在Mockito有什么办法我设置一个规则来在调用特定对象类型的属性时返回一个值吗?

时间:2016-07-12 22:06:54

标签: java testing mockito

我正在努力做到这一点(我确定有办法,但我无法弄明白)。

问题:

我的班级中有一个私有方法,该类是使用@InjectedMocks注入的。

私有方法调用服务并从私有对象发送属性作为参数。

像这样的东西

$scope.uniquelogo + '.' + file.name.substring(file.type.lastIndexOf('/') + 1, file.name.length)

问题在于我的对象并不那么容易,而且它有一个注释可以赋予它价值。看起来像@InjectedMocks,永远不会分配值,myObject始终为null。

由于方法和对象都是私有的,我不能只分配值(我避免为它们添加公共设置器)。

我的方法:

我想嘲笑这样的事情:

private MyObject myObject = new Object();

public void main(){
    doSomething();
}

private void doSomething(){
   someService(mObject.getValue);
}

所以,我会在考试时避免使用NP。

是否可以使用mockito?

还有更优雅的方法吗?

2 个答案:

答案 0 :(得分:1)

我假设你的代码示例中有一些错误。

以下实际上有效并打印" foobar":尝试将其与您的实际代码进行比较,以查看您忘记的内容。

<label for="jeux_plan"><input id="jeux" name="pieceafournir[]" value="jeux" type="checkbox" ><div ><h4>{{trans('app.jeux')}}</h4></div></label>
<label for="photocopin"><input id="photocopie" type="checkbox" name="pieceafournir[]" value="photocopie" ><div ><h4>{{trans('app.photocopie')}}</h4> </div></label>
<label for="contrat"> <input id="contrat" type="checkbox" name="pieceafournir[]" value="contrat" ><div ><h4>{{trans('app.contrat')}}</h4></div></label>
<label for="certificat"><input id="certificat" type="checkbox" name="pieceafournir[]" value="certificat" ><div ><h4>{{trans('app.certificat')}}</h4></div></label>
<label for="plan"><input id="plan" type="checkbox" name="pieceafournir[]" value="plan" ><div ><h4>{{trans('app.plan')}}</h4></div></label>
<label for="cahier"><input id="cahier" type="checkbox" name="pieceafournir[]" value="cahier" ><div ><h4>{{trans('app.cahier')}}</h4></div></label>
<label for="demande"><input id="demande" type="checkbox" name="pieceafournir[]" value="demande_autorisation" ><div ><h4>{{trans('app.demande')}}</h4></div></label>
<label for="identification"><input id="identification" type="checkbox" value="identification" name="pieceafournir[]" ><div ><h4>{{trans('app.identification')}}</h4></div></label>

答案 1 :(得分:0)

您可以使用PowerMock.createPartialMock和方法调用的代理单独模拟对象或方法。 例如上面的代码

when(any(MyObject).class).getValue().thenReturn("something");

应该是

when(mockedObject).methodCall().thenReturn("something");