0

I am trying to create a JUnit test for my method. I have a method

public a(int a, int b){
    a.setA(12);
    Injec inj = new Injec();
    inj.check();
    return (a*b);
}

I want to skip this section because it use HTTP request

Injec inj = new Injec();
inj.check();

I am using

when(Matchers.<Injec> anyObject().check()).thenReturn(null);

But it's giving me exception

Tunaki
  • 132,869
  • 46
  • 340
  • 423
vs7
  • 581
  • 5
  • 18
  • Can you show the exception you are getting? – Karl Gjertsen Nov 27 '15 at 13:19
  • The argument you pass to `when` has to be a mock or a spy, not a matcher, so this won't work. I wrote [an article about mocking object creation](https://code.google.com/p/mockito/wiki/MockingObjectCreation) a few years ago on the Mockito wiki. You may find it helpful for what you're trying to achieve here. – Dawood ibn Kareem Nov 28 '15 at 08:49

2 Answers2

3

With Mockito, you won't be able to do that with your current code.

The problem is that the method a creates a new Injec object itself, directly by calling the default constructor. There's no way for Mockito to mock that new instance since it can't have any control over it.

As such, you need to refactor your code. There are a couples of possible solutions:

  • pass the Injec instance as parameter to the a method. This way, you can mock the instance and give a mock to the method.
  • inject the Injec instance into your class (with a constructor injection for example).

If you are using JMockit, as noted by @Rogério, this is possible and you just need to add @Mocked Injec to your test class and the Injec instance will be mocked when it is created.

Tunaki
  • 132,869
  • 46
  • 340
  • 423
  • This is why `Inversion of Control` was invented : http://stackoverflow.com/questions/9403155/what-is-dependency-injection-and-inversion-of-control-in-spring-framework – Guillaume F. Nov 27 '15 at 14:31
0

Using JMockit you can mock your Injec class as follows:

@RunWith(JMockit.class)
public class MyTest
{
    private ClassToTest underTest;

    @Test
    public void testA(@Mocked Injec injec) {
        underTest.a(10, 20);

        // your assertions
    }
}
Rogério
  • 16,171
  • 2
  • 50
  • 63
Pith
  • 3,706
  • 3
  • 31
  • 44