How to write JUnit test with Spring Autowire? How to write JUnit test with Spring Autowire? spring spring

How to write JUnit test with Spring Autowire?


Make sure you have imported the correct package. If I remeber correctly there are two different packages for Autowiring. Should be :org.springframework.beans.factory.annotation.Autowired;

Also this looks wierd to me :

@ContextConfiguration("classpath*:conf/components.xml")

Here is an example that works fine for me :

@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(locations = { "/applicationContext_mock.xml" })public class OwnerIntegrationTest {    @Autowired    OwnerService ownerService;    @Before    public void setup() {        ownerService.cleanList();    }    @Test    public void testOwners() {        Owner owner = new Owner("Bengt", "Karlsson", "Ankavägen 3");        owner = ownerService.createOwner(owner);        assertEquals("Check firstName : ", "Bengt", owner.getFirstName());        assertTrue("Check that Id exist: ", owner.getId() > 0);        owner.setLastName("Larsson");        ownerService.updateOwner(owner);        owner = ownerService.getOwner(owner.getId());        assertEquals("Name is changed", "Larsson", owner.getLastName());    }


I've done it with two annotations for test class: @RunWith(SpringRunner.class) and @SpringBootTest.Example:

@RunWith(SpringRunner.class )@SpringBootTestpublic class ProtocolTransactionServiceTest {    @Autowired    private ProtocolTransactionService protocolTransactionService;}

@SpringBootTest loads the whole context, which was OK in my case.


A JUnit4 test with Autowired and bean mocking (Mockito):

// JUnit starts with spring context@RunWith(SpringRunner.class)// spring loads context configuration from AppConfig class@ContextConfiguration(classes = AppConfig.class)// overriding some properties with test values if you need@TestPropertySource(properties = {        "spring.someConfigValue=your-test-value",})public class PersonServiceTest {    @MockBean    private PersonRepository repository;    @Autowired    private PersonService personService; // uses PersonRepository        @Test    public void testSomething() {        // using Mockito        when(repository.findByName(any())).thenReturn(Collection.emptyList());        Person person = new Person();        person.setName(null);        // when        boolean found = personService.checkSomething(person);        // then        assertTrue(found, "Something is wrong");    }}