简体   繁体   English

Mockito-仅模拟一种方法

[英]Mockito - mocking only a method

So I have following problem: 所以我有以下问题:

I have a class and I created three objects of it (obj1, obj2, obj3). 我有一个类,并创建了它的三个对象(obj1,obj2,obj3)。 I assigned them various values via setter-methods in my Testclass, since they will be used in a list later on. 我通过Testclass中的setter-methods为它们分配了各种值,因为稍后将在列表中使用它们。

The thing is, the class has a method, which returns a boolean, and it gets the value via SAP-Services, which of course I don't want to mock. 关键是,该类具有一个方法,该方法返回一个布尔值,并且它通过SAP服务获取值,当然我不想模拟它。 So of course I want to use the when-method from Mockito to make sure, they return different values, because the class I want to test, sorts the files based on what they return on the method. 因此,当然,我想使用Mockito中的when方法来确保它们返回不同的值,因为我要测试的类根据文件在方法上返回的内容对文件进行排序。

when(obj1.method()).thenReturn(true);
when(obj2.method()).thenReturn(false);
when(obj3.method()).thenReturn(true);

To do this, I need to mock the objects: 为此,我需要模拟对象:

@mock
private Object obj1;

and in my setUp: 在我的设置中:

obj1 = mock(Object.class);

But when I do this, it won't allow me to set values for the objects. 但是,当我这样做时,将不允许我设置对象的值。

How do I do that nonetheless, I need to fill the objects with some things, I can't leave them blank. 尽管如此,我该怎么做,我需要用一些东西填充对象,我不能将它们留空。 It's only that there's no other way to set the return-value of the method than to mock the object.. 只是除了模拟对象之外,没有其他方法可以设置方法的返回值。

Never use @Mock obj1 and obj1 = mock(Object.class); 永远不要使用@Mock obj1obj1 = mock(Object.class); together... they are both doing the same thing and one is overriding the other. 在一起...他们俩都在做同一件事,而一个人却在压倒另一个。

If you use @RunWith(MockitoJunitRunner.class) and @Mock you don't need mock(...) (most of the time). 如果您使用@RunWith(MockitoJunitRunner.class)@Mock ,则不需要mock(...) (大多数时间)。

Also, I doubt that obj1 should be of type Object, I'm guessing it should be a more specific interface type. 另外,我怀疑obj1应该是Object类型,我猜测它应该是更特定的接口类型。

If you want to mock only some methods of the object, you can use @Spy The method should be mocked a bit differently in this case though doReturn(true).when(obj1).method(); 如果只想模拟对象的某些方法,则可以使用@Spy。在这种情况下,应该通过doReturn(true).when(obj1).method();来模拟该方法。

See http://docs.mockito.googlecode.com/hg/1.9.5/org/mockito/Spy.html for more info 有关更多信息,请参见http://docs.mockito.googlecode.com/hg/1.9.5/org/mockito/Spy.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM