繁体   English   中英

如何用 Spring Autowire 编写 JUnit 测试?

[英]How to write JUnit test with Spring Autowire?

以下是我使用的文件:

组件.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>

ServiceImpl.java

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

    @Autowired
    private MyDAO myDAO;

    public void getData() {...}    
}

ServiceImplTest.java

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

    @Test
    public void testMyFunction() {...}
}

错误:

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]

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

这对我来说也很奇怪:

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

这是一个对我来说很好的例子:

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

    }

我已经为测试类添加了两个注释: @RunWith(SpringRunner.class)@SpringBootTest 例子:

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

    @Autowired
    private ProtocolTransactionService protocolTransactionService;
}

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

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

至少在 Spring 2.1.5 中,XML 文件可以方便地被注释替换。 小猪支持@Sembrano的回答,我有这个。 “看,没有 XML”。

看来我已经在@ComponentScan 中列出了我需要@Autowired 的所有类

@RunWith(SpringJUnit4ClassRunner.class)
@ComponentScan(
    basePackageClasses = {
            OwnerService.class
            })
@EnableAutoConfiguration
public class OwnerIntegrationTest {
    
    @Autowired
    OwnerService ownerService;
    
    @Test
    public void testOwnerService() {
       Assert.assertNotNull(ownerService);
    }
}

我认为您的代码库中的某个地方是您@Autowiring具体类ServiceImpl ,您应该在其中自动装配它的接口(大概是MyService )。

您应该在测试资源文件夹中创建另一个 XML-spring 配置文件,或者只是复制旧的,看起来不错,但是如果您尝试启动 Web 上下文来测试微服务,只需将以下代码作为您的主测试类并从中继承:

@WebAppConfiguration
@RunWith(SpringRunner.class)
@ContextConfiguration(locations = "classpath*:spring-test-config.xml")
public abstract class AbstractRestTest {
    @Autowired
    private WebApplicationContext wac;
}

对于 Spring 5.x 和 JUnit 5,编写单元测试是完全不同的。

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

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

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

@Configuration
public class FooConfig
{
    @Bean
    public String foo1() { return "Foo1"; }
}

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

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

您可以使用@Import注释。 它比使用@ComponentScan注释更具可读性和更短。

import org.springframework.context.annotation.Import;

@Import(value = {MyService.class, MyInjectedService.class})
public class JUnitTest {
    @Autowired
    private MyService service;

    // ...
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM