gpt4 book ai didi

java - 单元测试用例中的空 @Autowired beans

转载 作者:搜寻专家 更新时间:2023-11-01 03:00:09 24 4
gpt4 key购买 nike

我正在尝试自动连接一个 spring 管理的 bean 以在我的单元测试用例中使用。但是 Autowiring 的 bean 总是空的。以下是我的设置。

my unit test class

@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
}

}

spring managed bean

package com.myproject.business;

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

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

}

context for unit test case

<?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/>
<context:component-scan base-package="com.myproject.business"/>
</beans>

我见过很多问题,所有问题都给出了我已经合并到我的代码中的答案。有人能告诉我我错过了什么吗?我正在使用 intellij 14 来运行我的测试用例。

最佳答案

你有这样的代码:

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

您真的想使用 MockitoJUnitRunner 吗,因为我在类里面看不到更多模拟。

请尝试运行 JUnit

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

编辑 -

@RunWith(SpringJUnit4ClassRunner.class) 使使用 @ContextConfiguration(..) 声明的所有依赖项对使用它的类可用。

例如,在您的情况下,您在类(class)上有 @RunWith(SpringJUnit4ClassRunner.class) - SMSGateway。因此,它使所有这些依赖项都可以使用 @ContextConfiguration(locations = "classpath*:business-context-test.xml") 配置的 SMSGateway

这有助于在您的类 SMSGateway 中 Autowiring “smsGateway”。当您使用 @RunWith(MockitoJUnitRunner.class) 时,此依赖项不可用于 Autowiring ,因此 spring 会提示。如果您在应用程序中使用 Mockito,则需要 MockitoJUnitRunner.class。由于您没有模拟任何类(class),因此您现在不需要 MockitoJUnitRunner。

请看-Mockito, JUnit and Spring 以获得更多说明。

看看http://www.alexecollins.com/tutorial-junit-rule/ .这将帮助您了解“@Runwith”和“@ContextConfiguration”注释在幕后是如何工作的。

关于java - 单元测试用例中的空 @Autowired beans,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37161573/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com