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());
}
}
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.
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);
}
}
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.