How to write JUnit test with Spring Autowire?

前端 未结 6 461
孤城傲影
孤城傲影 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());
    
        }
    

提交回复
热议问题