How to write JUnit test with Spring Autowire?

前端 未结 6 462
孤城傲影
孤城傲影 2020-12-03 06:45

Here are the files that I use:

component.xml




        
相关标签:
6条回答
  • 2020-12-03 07:08

    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());
    
        }
    
    0 讨论(0)
  • 2020-12-03 07:09

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

    // JUnit starts spring context
    @RunWith(SpringRunner.class)
    // spring load 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");
        }
    }
    
    
    0 讨论(0)
  • 2020-12-03 07:12

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

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

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

    0 讨论(0)
  • 2020-12-03 07:16

    I think somewhere in your codebase are you @Autowiring the concrete class ServiceImpl where you should be autowiring it's interface (presumably MyService).

    0 讨论(0)
  • 2020-12-03 07:27

    You should make another XML-spring configuration file in your test resource folder or just copy the old one, it looks fine, but if you're trying to start a web context for testing a micro service, just put the following code as your master test class and inherits from that:

    @WebAppConfiguration
    @RunWith(SpringRunner.class)
    @ContextConfiguration(locations = "classpath*:spring-test-config.xml")
    public abstract class AbstractRestTest {
        @Autowired
        private WebApplicationContext wac;
    }
    
    0 讨论(0)
  • 2020-12-03 07:33

    In Spring 2.1.5 at least, the XML file can be conveniently replaced by annotations. Piggy backing on @Sembrano's answer, I have this. "Look ma, no XML".

    It appears I to had list all the classes I need @Autowired in the @ComponentScan

    @RunWith(SpringJUnit4ClassRunner.class)
    @ComponentScan(
        basePackageClasses = {
                OwnerService.class
                })
    @EnableAutoConfiguration
    public class OwnerIntegrationTest {
        
        @Autowired
        OwnerService ownerService;
        
        @Test
        public void testOwnerService() {
           Assert.assertNotNull(ownerService);
        }
    }
    
    0 讨论(0)
提交回复
热议问题