English 中文(简体)
Mockito: How to easily stub a method without mocking all parameters
原标题:

I have a method i d like to stub but it has a lot of parameters. How can i avoid mocking all parameters but still stub the method.

Ex:

//Method to stub
public void myMethod(Bar bar, Foo foo, FooBar fooBar, BarFoo barFoo, .....endless list of parameters..);
最佳回答

I don t quite follow what problem you re having using Mockito. Assuming you create a mock of the interface that contains your myMethod() method, you can then verify only the parameters to the method that you are interested in. For example (assuming the interface is called MyInterface and using JUnit 4):

@Test
public void test() {
    MyInterface myInterface = mock(MyInterface.class);
    FooBar expectedFooBar = new FooBar();        

    // other testing stuff

    verify(myInterface).myMethod(any(), any(), eq(expectedFooBar), any(), ...);
}

You ll need to do a static import on the Mockito methods for this to work. The any() matcher doesn t care what value has been passed when verifying.

You can t avoid passing something for every argument in your method (even if it s only NULL).

问题回答

use mockito.any

if myobj mymethod accepts string, string, bar for instance

to stub a call

Mockito.when(myojb.myMethod(Mockito.anyString(),Mockito.anyString(),Mockito.any(Bar.class)))
    .thenReturn(amockedobject);

to verify SteveD gave the answer already

Mockito.verify(myojb).myMethod(
    Mockito.anyString(),Mockito.anyString(),Mockito.any(Bar.class)));

Create a wrapper class which calls the real method and fills in all the arguments but the ones you supply (a.k.a "delegation").

And at the next opportunity, file a bug against the project asking to move the parameters to a config object.





相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签