相关疑难解决方法(0)

将Mockito模拟注入Spring bean

我想将一个Mockito模拟对象注入一个Spring(3+)bean中,以便使用JUnit进行单元测试.我的bean依赖项目前通过@Autowired在私有成员字段上使用注释来注入.

我考虑过使用ReflectionTestUtils.setField但我希望注入的bean实例实际上是一个代理,因此不会声明目标类的私有成员字段.我不希望为依赖创建一个公共setter,因为我将修改我的界面纯粹是为了测试的目的.

我遵循了Spring社区给出的一些建议,但是没有创建模拟并且自动连线失败:

<bean id="dao" class="org.mockito.Mockito" factory-method="mock">
    <constructor-arg value="com.package.Dao" />
</bean>
Run Code Online (Sandbox Code Playgroud)

我目前遇到的错误如下:

...
Caused by: org...NoSuchBeanDefinitionException:
    No matching bean of type [com.package.Dao] found for dependency:
    expected at least 1 bean which qualifies as autowire candidate for this dependency.
    Dependency annotations: {
        @org...Autowired(required=true),
        @org...Qualifier(value=dao)
    }
at org...DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(D...y.java:901)
at org...DefaultListableBeanFactory.doResolveDependency(D...y.java:770)
Run Code Online (Sandbox Code Playgroud)

如果我将constructor-arg值设置为无效,则在启动应用程序上下文时不会发生错误.

junit spring annotations dependency-injection mockito

276
推荐指数
13
解决办法
23万
查看次数

如何在Junit中使用@InjectMocks和@Autowired注释

我有一个A类,它使用3个不同的类和自动装配

public class A () {

    @Autowired
    private B b;

    @Autowired
    private C c;

    @Autowired
    private D d;
}
Run Code Online (Sandbox Code Playgroud)

在测试它们时,我希望只有2个类(B&C)作为模拟,并且将D类自动装配为正常运行,此代码对我不起作用:

@RunWith(MockitoJUnitRunner.class)
public class aTest () {

    @InjectMocks
    private A a;

    @Mock
    private B b;

    @Mock
    private C c;

    @Autowired
    private D d;
}
Run Code Online (Sandbox Code Playgroud)

甚至可以这样做吗?

java junit spring mocking mockito

36
推荐指数
3
解决办法
3万
查看次数

被测单元:Impl还是接口?

假设我有实现它的接口和实现类,我想为此编写单元测试.我应该测试什么接口或Impl?

这是一个例子:

public interface HelloInterface {
    public void sayHello();
}


public class HelloInterfaceImpl implements HelloInterface {
    private PrintStream target = System.out;


    @Override
    public void sayHello() {
        target.print("Hello World");

    }

    public void setTarget(PrintStream target){
        this.target = target;
    }
}
Run Code Online (Sandbox Code Playgroud)

所以,我有HelloInterface和HelloInterfaceImpl来实现它.什么是被测单元接口或Impl?

我认为它应该是HelloInterface.考虑下面的JUnit测试草图:

public class HelloInterfaceTest {
    private HelloInterface hi;

    @Before
    public void setUp() {
        hi = new HelloInterfaceImpl();
    }

    @Test
    public void testDefaultBehaviourEndsNormally() {
        hi.sayHello();
        // no NullPointerException here
    }

    @Test
    public void testCheckHelloWorld() throws Exception {
        ByteArrayOutputStream out = new ByteArrayOutputStream(); …
Run Code Online (Sandbox Code Playgroud)

java unit-testing dependency-injection mockito

31
推荐指数
3
解决办法
2万
查看次数

使用MockitoJUnitRunner.class而不是SpringJUnit4ClassRunner.class

我有一个关于使用的问题SpringJUnit4ClassRunner.对于纯Junits或单元测试用例,我们是否应该使用基于Spring的注释,例如@Autowired,SpringJUnit4ClassRunner或者我们是否应该只使用Test类顶部MockitoJUnitRunner@RunWith注释?

我的意思是更换

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({ "classpath:test-applicationContext.xml" })
Run Code Online (Sandbox Code Playgroud)

只是

@RunWith(MockitoJUnitRunner.class)
Run Code Online (Sandbox Code Playgroud)

在班上.这个对我有用.

在Junits中,我们通常不会进行任何外部调用,例如调用DB或调用其他Web服务.我们必须使用@Mock此服务对象上的注释来模拟这些外部调用.然后创建我们正在测试的类的真实对象,这取决于这些模拟.然后我们可以@InjectMocks在真实对象上使用它,以便它将被注入模拟对象.

示例服务-A->呼叫 - >服务-B->呼叫 - >服务-C

在测试A时,我们应该在测试Service-B时模拟服务B,我们应该模拟Service-C.

一些代码片段

@RunWith(MockitoJUnitRunner.class)
public class TestServiceA {
    @Mock
    B mockObj;

    @InjectMocks
    A realObj;

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

所以,我觉得对于Unit测试用例,我们不需要依赖Spring容器来为我们提供我们正在测试的类的实例.

请提出你的建议.

使用SpringJUnit4ClassRunner.class而不是MockitoJUnitRunner.class

java junit unit-testing

16
推荐指数
1
解决办法
1万
查看次数

单元测试用例中的空@Autowired bean

我正在尝试自动连接一个 spring 管理的 bean 以在我的单元测试用例中使用。但是自动装配的 bean 始终为 null。下面是我的设置。

我的单元测试课

@RunWith(MockitoJUnitRunner.class)
@ContextConfiguration(locations = "classpath*:business-context-test.xml")
public class SMSGatewayTest {

    @Autowired
    @Qualifier("mySMSImpl")
    private ISMSGateway smsGateway;

        @Test
        public void testSendTextMessage() throws Exception {
          smsGateway.sendText(new TextMessage("TEST")); 
          //  ^___________ this is null, even though I have set ContextConfiguration 
        }

}
Run Code Online (Sandbox Code Playgroud)

春季管理豆

package com.myproject.business;

@Component("mySMSImpl")
public class MySMSImpl implements ISMSGateway {

    @Override
    public Boolean sendText(TextMessage textMessage ) throws VtsException {
          //do something
    }

}
Run Code Online (Sandbox Code Playgroud)

单元测试用例的上下文

<?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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd

       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">


       <context:annotation-config/> …
Run Code Online (Sandbox Code Playgroud)

java junit spring unit-testing intellij-idea

6
推荐指数
1
解决办法
9685
查看次数

Spring中的单元测试:将依赖项注入正在测试的组件中

我有一个非常简单的休息控制器:

@RestController
public class MyController {
    @Autowired
    public Logger logger;
Run Code Online (Sandbox Code Playgroud)

通过以下配置注入记录器依赖项:

@Configuration
public class MyConfig {
    @Bean
    public Logger logger() {
        return LoggerFactory.getLogger(MyController.class);
    }
Run Code Online (Sandbox Code Playgroud)

如果我运行包含控制器的Spring应用程序,那么一切正常.但是,在运行单元测试时,我无法设法实现此依赖注入.在这种情况下,我有以下测试配置:

@Configuration
@Profile("test")
public class MyTestConfig {
    @Bean
    public Logger logger() {
        return LoggerFactory.getLogger(MyCOntroller.class);
    }
Run Code Online (Sandbox Code Playgroud)

这是我的单元测试代码的相关部分:

@RunWith(MockitoJUnitRunner.class)
@ContextConfiguration(classes = MyTestConfig.class)
@ActiveProfiles("test")
public class MyContollerTest {
Run Code Online (Sandbox Code Playgroud)

但是,记录器对象没有"自动装配" MyController(请注意,我不想模拟记录器对象),这会导致空指针引用.

我错过了什么?

java spring unit-testing

5
推荐指数
1
解决办法
2万
查看次数

在 Java 和 Spring 中对 REST API 进行单元测试

我有一个简单的 Java Spring REST API 应用程序,但我不知道如何对其进行单元测试。我已经阅读了 JUnit 和 Mockito 的文档,但我无法弄清楚。

这是 StudentController 类中的 post 方法

@RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
    public void insertStudent(@RequestBody Student student){
        studentService.insertStudent(student);
    }
Run Code Online (Sandbox Code Playgroud)

这是 StudentService 类中的 insertStudent 方法

public void insertStudent(Student student) {
        studentDao.insertStudent(student);
    }
Run Code Online (Sandbox Code Playgroud)

我使用 MySQL 作为数据库。我也应该使用数据库进行单元测试吗?我的意思是我不想要任何集成测试。我只想要单元测试。我在 Node.js 中使用 supertest 并且它会照顾所有,我也可以用 JUnit 或 Mockito 做到这一点吗?

java rest junit spring unit-testing

0
推荐指数
1
解决办法
1万
查看次数