从测试文件夹中的src文件夹弹出豆子

问题描述:

我的源文件夹中有作为bean公开的实用程序类。我想在我的junit 4编写的测试类中使用其中的一些实用程序。例如,我有一个实用程序类,它具有将对象编组为JSON字符串的方法。我想在我的测试类中注入这个实用程序bean。我无法使用Autowired注释来注入这些bean。我应该将所有这些类复制到测试文件夹吗?从测试文件夹中的src文件夹弹出豆子

编辑:

我想注入jsonUtil。下面是我的代码的样子。

import static org.junit.Assert.*; 

import java.math.BigDecimal; 

@RunWith(MockitoJUnitRunner.class) 
@SpringApplicationConfiguration(classes = ProxyApplicationMock.class) 
public class ProxyApplicationMock { 

    @Mock 
    public SoapClient soapClientMock; 

    private JsonUtil jsonUtil; 

主类

public class ProxyApplication { 

    public static void main(String[] args) { 
     SpringApplication.run(ProxyApplication.class, args); 
    } 
} 
+0

你应该表现出例如你的测试类的代码与Spring上下文配置,并告诉我们哪些你正在使用的Spring版本。 – Matt

+0

嗨马特,添加了代码,我使用的是Spring Boot。 –

+0

好的,看看我的回答,并告诉我是否有任何帮助。显示你的Spring配置文件也会有所帮助:'ProxyApplicationMock' – Matt

你的主要类可以通过你的测试类可以看到,但不是周围的其他方式。所以不,你不需要复制它们。

如果您的实用程序类在您的测试Spring上下文配置(该类或XML文件 - 在@ContextConfiguration中声明)中声明为Spring托管bean,该配置可能且可能应与您的主配置不同。

然后,您可以将它注入到任何Spring托管类中,如果它使用的是SpringJUnit4ClassRunner,那么它将包含您的测试类。

编辑:

要总结一下我们在评论中讨论的,主要的问题是,你的测试运行是不是SpringRunner(别名SpringJUnit4ClassRunner),因此JUnit是没有运行在Spring上下文测试。看看a test example here

最简单的测试用例将如下所示。

@RunWith(SpringRunner.class) 
@SpringBootTest 
public class CityRepositoryIntegrationTests { 
    @Autowired 
    private MySpringBean springBean; 
    //... 
} 

但是,像Spring Boot一样,经常会发生一些魔术。 @SpringBootTest是一个方便的注释,它会自动检测用@SpringBootConfiguration注解的类,这意味着如果您没有为您的测试配置特定的Spring配置,它将使用您的主要Spring配置,从而包含并实例化主应用程序的所有bean ,这通常不是我们想要的单元测试的原因,因为我们希望通过嘲笑它的依赖性来独立地测试一个类。

你可以做什么,是提供你想在你的测试,包括Spring的compenent类,例如:

@RunWith(SpringRunner.class) 
@SpringBootTest(classes = MySpringBean.class) 
public class CityRepositoryIntegrationTests { 
    @Autowired 
    private MySpringBean springBean; 

    @Mock 
    private MyMockedSpringBeanDependency mocked; 
    //... 
} 
+0

谢谢Matt。我正在使用杰克逊,但是我已经对我的util中的编组和解组部分进行了一些定制 –