Sumit
Sumit

Reputation: 878

How to pass mock parameter in a method using Mockito & Java

I have class like the following:

public class Service {
  public String method1 (class1, class2){
  //do something
  return result          //Returns a string based on something 
 }
}

I want to test the class Service by calling the method 'method1' with mocked parameter (objects of Class1 & Class2). I don't have any idea, how to do this using Mockito.Can anyone help me with the initial push ?

Upvotes: 1

Views: 23031

Answers (1)

Lorenzo Murrocu
Lorenzo Murrocu

Reputation: 688

If class1 and class2 are simple values or POJOs, you should just not mock them:

public class ServiceTest {

    Service service;

    @Before
    public void setup() throws Exception {
        service = new Service();
    }

    @Test
    public void testMethod1() throws Exception {
        // Prepare data
        Class1 class1 = new Class1();
        Class2 class2 = new Class2();
        // maybe set some values
        ....

        // Test
        String result = this.service.method1(class1, class2);

        // asserts here...
    }
}

If class1 and class2 are more complicated classes, like services, it is strange to pass them as arguments... However I don't want to discuss your design, so I will just write an example of how you can do it:

public class ServiceTest {

    Service service;

    @Mock Class1 class1Mock;
    @Mock Class2 class2Mock;

    @Before
    public void setup() throws Exception {
        MockitoAnnotations.initMocks(this);
        service = new Service();
    }

    @Test
    public void testMethod1() throws Exception {
        // Mock each invocation of the "do something" section of the method
        when(class1Mock.someMethod).thenReturn(someValue1);
        when(class2Mock.someMethod).thenReturn(someValue2);
        ....

        // Test
        String result = this.service.method1(class1Mock, class2Mock);

        // asserts here...
    }
}

Upvotes: 1

Related Questions