简体   繁体   中英

Inject object in injected service class using Mockito

I'm trying to write aa JUnit test for a service in our JavaEE7 application. The service class under test injects another service class which in turn injects yet another class. Here's my classes in short:

class ServiceA {
   ServiceB serviceB;
   public void methodA() {
     serviceB.methodB();
   }
}

class ServiceB {
   @Inject
   ServiceC serviceC;
   public void methodB() {
      serviceC.methodC();
   }
}

class ServiceC {
   public void methodC() {}
}

class TestServiceA {
   @Spy
   ServiceA serviceA;
   @InjectMocks
   ServiceB serviceB;
   @Before
   public void setUp() {
      serviceA.serviceB = mock(ServiceB.class);
   }

   @Test
   public void testServiceA() {
      serviceA.methodA();
   }
}

EDIT: Edited from original Logger question to general object question. The question is if it is possible or necessary to inject multiple levels of objects in my tests or if I should just mock the first injected service and capture all method calls to subsequent service with when-Expressions?

You aim to test for instance that methodB is really called when you use serviceA.methodA() .

The following code does this:

import javax.inject.Inject;

public class ServiceA {

    @Inject
    ServiceB serviceB;

    public void methodA() {
        serviceB.methodB();
    }
}

import javax.inject.Inject;

public class ServiceB {

    @Inject
    Logger log;

    public void methodB() {
        log.debug("log message");
    }
}

import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.slf4j.Logger;

public class ServiceTest {

    /**
     * Create an instance of the class ServiceA.
     */
    @InjectMocks
    private ServiceA serviceA;

    /**
     * Create a fake instance of ServiceB.
     */
    @Mock
    private ServiceB serviceB;

    /**
     * Create a fake instance of Logger.
     */
    @Mock
    private Logger log;

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
    }

    /**
     * Verify that methodB is called.
     */
    @Test
    public void testServiceA() {
        serviceA.methodA();
        verify(serviceB, times(1)).methodB();
    }
}

Here, the Logger must be a mock too, otherwise you will get a NPE.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM