Define Spring Beans inline JUnit test

Sometimes you like to define some Spring beans in a JUnit test and do not want to create extra files for that. You can do that be defining the beans inline in your test class like this:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class MyServiceTest {

    @Configuration
    @EnableCaching
    static class SpringConfig {

        @Bean
        public MyService myService() {
            MyServiceImpl myServiceImpl = new MyServiceImpl();
            myServiceImpl.setOtherService(otherService());
            
            return myServiceImpl;
        }
        
        @Bean
        public OtherService otherService() {
            return Mockito.mock(OtherService.class);
        }        
    }

    @Autowired
    MyService myService; 

    @Autowired
    OtherService otherService;
   
    @Test
    public void testSomething() {
        ...
    }
}

This will define a Spring bean MyService and OtherService and it will also inject OtherService into MyService.