Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock spring injected classes using JMockit

My code:

class A extends X {
    @Autowired
    B b;

    @Override
    method() {
        //do something
        b.callMethodInB;
        //do something
    }

}

class B extends X {
    @Autowired
    C c;

    @Override
    method() {
        //do something
        c.callMethodInC;
       //do something
    }

}

I need to test method() in A. So how to mock B. I'm using Junit4 and Jmockit.

like image 566
Ranjith Avatar asked Jun 28 '12 10:06

Ranjith


People also ask

How do you mock injected objects?

Mockito @InjectMocks annotations allow us to inject mocked dependencies in the annotated class mocked object. This is useful when we have external dependencies in the class we want to mock. We can specify the mock objects to be injected using @Mock or @Spy annotations.

What is the difference between JMockit and Mockito?

JMockit will be the chosen option for its fixed-always-the-same structure. Mockito is more or less THE most known so that the community will be bigger. Having to call replay every time you want to use a mock is a clear no-go, so we'll put a minus one for EasyMock. Consistency/simplicity is also important for me.

How do you mock a spring bean?

We can use the @MockBean to add mock objects to the Spring application context. The mock will replace any existing bean of the same type in the application context. If no bean of the same type is defined, a new one will be added.


1 Answers

Try something like this:

import org.junit.*;
import mockit.*;

public class ATest
{
    @Tested A a;
    @Injectable B b;

    @Test
    public void testMethod()
    {
        a.method();

        new Verifications() {{ b.callMethodInB(); }};
    }
}

JMockit automatically instantiates A with an injected B instance (from the mock field b), setting it to the a field in the test class. This is independent of the DI framework used (Spring).

like image 117
Rogério Avatar answered Sep 22 '22 01:09

Rogério