如何使用Spring Autowire编写JUnit测试?

Pre*_*raj 25 java spring junit4 playframework-2.0

这是我使用的文件:

component.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jee="http://www.springframework.org/schema/jee"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
         http://www.springframework.org/schema/context
         http://www.springframework.org/schema/context/spring-context-3.0.xsd 
         http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd">

    <context:component-scan
        base-package="controllers,services,dao,org.springframework.jndi" />
</beans>
Run Code Online (Sandbox Code Playgroud)

ServiceImpl.java

@org.springframework.stereotype.Service
public class ServiceImpl implements MyService {

    @Autowired
    private MyDAO myDAO;

    public void getData() {...}    
}
Run Code Online (Sandbox Code Playgroud)

ServiceImplTest.java

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath*:conf/components.xml")
public class ServiceImplTest{

    @Test
    public void testMyFunction() {...}
}
Run Code Online (Sandbox Code Playgroud)

错误:

16:22:48.753 [main] ERROR o.s.test.context.TestContextManager - Caught exception while allowing TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionListener@2092dcdb] to prepare test instance [services.ServiceImplTest@9e1be92]
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'services.ServiceImplTest': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private services.ServiceImpl services.ServiceImplTest.publishedServiceImpl; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [services.ServiceImpl] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:287) ~[spring-beans.jar:3.1.2.RELEASE]
Run Code Online (Sandbox Code Playgroud)

Sem*_*ano 19

确保您已导入正确的包.如果我记得正确,有两种不同的自动装配包.应该 :org.springframework.beans.factory.annotation.Autowired;

这看起来对我来说很奇怪:

@ContextConfiguration("classpath*:conf/components.xml")
Run Code Online (Sandbox Code Playgroud)

这是一个适合我的例子:

@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());

    }
Run Code Online (Sandbox Code Playgroud)

  • 什么是“/applicationContext_mock.xml”? (7认同)

小智 8

我已经完成了测试类的两个注释:@RunWith(SpringRunner.class)@SpringBootTest. 例子:

@RunWith(SpringRunner.class )
@SpringBootTest
public class ProtocolTransactionServiceTest {

    @Autowired
    private ProtocolTransactionService protocolTransactionService;
}
Run Code Online (Sandbox Code Playgroud)

@SpringBootTest 加载整个上下文,这在我的情况下是可以的。


Ser*_*nov 7

使用 Autowired 和 bean 模拟 (Mockito) 的 JUnit4 测试:

// 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");
    }
}

Run Code Online (Sandbox Code Playgroud)


Mic*_*kis 6

对于 Spring 5.x 和 JUnit 5,编写单元测试有很大不同。

我们必须使用@ExtendWith注册Spring扩展(SpringExtension)。这使得 Spring 发挥作用,它激活部分应用程序上下文(实例化并管理来自选定配置类的 bean)。

@SpringBootTest请注意,这与加载完整应用程序上下文的效果不同(恕我直言,不能将其视为单元测试)。

例如,让我们创建一个配置类FooConfig,它生成一个名为 的 bean foo1

@Configuration
public class FooConfig
{
    @Bean
    public String foo1() { return "Foo1"; }
}
Run Code Online (Sandbox Code Playgroud)

现在,让我们编写一个注入的 JUnit 5 测试用例foo1

import static org.junit.jupiter.api.Assertions.*;
// ... more imports ...

@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = {
    helloworld.config.FooConfig.class,
})
class FooTests
{
    @BeforeAll
    static void setUpBeforeClass() throws Exception {}

    @AfterAll
    static void tearDownAfterClass() throws Exception {}

    @BeforeEach
    void setUp() throws Exception {}

    @AfterEach
    void tearDown() throws Exception {}
    
    @Autowired
    private String foo1;
    
    @Test
    void test()
    {
        assertNotNull(foo1);
        System.err.println(foo1);
    }
}
Run Code Online (Sandbox Code Playgroud)