Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inject a service into junit test

Tags:

java

junit

spring

I'd like to know about the different possibilities/tools to inject a service into a JUnit test so I can use it without having to get a new instance (in fact my service is a singleton) :

public class ServiceTest {

    // Service to inject
    private IMyService someService;

    @Test
    public void methodTest() {
        // test body ...
        assertTrue(someService.someServiceMethod());
    }
}
like image 482
medmoufahim Avatar asked Oct 16 '25 06:10

medmoufahim


2 Answers

You can use the JMockit mocking toolkit. JMockit is a Java framework for mocking objects in tests (JUnit / TestNG)

See the example below

@RunWith(JMockit.class)
public class ServiceTest {

    @Tested
    private Service myService;

    @Injectable
    private AnotherService mockAnotherService;

    @Test
    public void methodTest() {
        new Expectations() {{
           mockAnotherService.someMethod("someValue"); result = true;
       }};

        assertTrue(myService.someMethod());
    }
}

The Service to be tested should be annotated with @Tested. If the Service to be tested invokes other services, these should be annotated with @Injectable (mocks)

In the above example, the myService.someMethod invokes the AnotherService.someMethod and passes the String someValue. JMockit runs the myService's method code and when it reaches the mockAnotherService call, it makes that call to return true

mockAnotherService.someMethod("someValue"); result = true;

Read the JMockit documentation for more info.

like image 118
Ioannis Barakos Avatar answered Oct 18 '25 21:10

Ioannis Barakos


You can use dependency injection to insert Mockito mocks into Spring Beans for unit testing.

Look this: https://www.baeldung.com/injecting-mocks-in-spring and https://www.baeldung.com/java-spring-mockito-mock-mockbean

@ActiveProfiles("test")
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = MocksApplication.class)
public class UserServiceTest {

    @Autowired
    private UserService userService;

    @Autowired
    private NameService nameService;

    @Test
    public void whenUserIdIsProvided_thenRetrievedNameIsCorrect() {
        Mockito.when(nameService.getUserName("SomeId")).thenReturn("Mock user name");
        String testName = userService.getUserName("SomeId");
        Assert.assertEquals("Mock user name", testName);
    }
}
like image 20
João Zarate Avatar answered Oct 18 '25 20:10

João Zarate



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!