kandarp
kandarp

Reputation: 1101

How to mock only one dependency of test class in spring

I have a class, which has a lot of dependencies.

@Service
public class TestClass {

    @Inject
    private DependencyA dependencyA;

    @Inject
    private DependencyB dependencyB;

    @Inject
    private DependencyC dependencyC;
    // .
    // .    
    // .    
    // .
    @Inject
    private DependencyZ dependencyZ;

    public boolean testMethod() {
        try {
            dependencyA.methodA();
            dependencyB.methodB();
            dependencyC.methodC();
            dependencyD.methodD();
            return true;
        } catch (StaleObjectStateException e) {
            return false;
        }
    }
}

Now I want to mock one of the dependencies and throw exception to test the catch block of this class.

So following is my test, where I mock dependencyB and throw StaleObjectStateException when dependencyB.methodB(); called.

public class TestClassIT {

    @InjectMocks
    private TestClass testClass;

    @InjectMocks
    private CustomRuleEngine customRuleEngine;

    @Mock
    private DependencyB dependencyB;

    @Before
    public void init() {
        MockitoAnnotations.initMocks(TestClass.class);
    }

    @Test
    public void testOnSuccessRuleAfterCreate() throws Exception {
        setupRequestContextWithFullPermission();
        when(dependencyB.methodB(any())).thenThrow(new StaleObjectStateException("f", "f"));
        // and expect exception.
    }
}

However, it doesn't work because all other dependencies of TestClass are injected as a null. How to solve this? As I mentioned this class has a lot of dependencies and I can't mock each. The requirement is just of mock dependencyB.methodB();

Upvotes: 1

Views: 880

Answers (2)

Tamás Pollák
Tamás Pollák

Reputation: 223

You have to define all your dependencies as mocks, not just DependencyB, so Mockito can do the injection. Even if you do not mock their methods, this way, there won't be null fields in your TestClass.

@Mock
private DependencyA dependencyA;

@Mock
private DependencyB dependencyB;

@Mock
private DependencyC dependencyC;

Upvotes: 1

EricSchaefer
EricSchaefer

Reputation: 26330

This is one of the cases where property injection is hurting.

Change TestClass to use constructor injection. Then you can instantiate it in your test yourself and inject whatever you want.

Upvotes: 2

Related Questions