我无法通过从 application-test.properties
文件中读取测试来传递该字段到模拟方法。
@RunWith(SpringRunner.class)
@TestPropertySource("classpath:application-test.properties")
public class ReportImplTest {
@Mock
private Dependencies dependencies;
@InjectMocks
private ReportImplTest underTest;
@Test
public void testgetReports() {
List<String> reps= underTest.getReports(anyString());
}
}
这是模拟方法的实际类
@Component
public class ReportImpl {
@Value("${REP_PROPNAME}")
String reppropname;
public List<String> getReports(String rep){
return staticUtilityclass.process(staticUtilityclass.transform(reppropname,"Reports"));
}
}
reppropname 在 getReports
方法中为 null。测试在测试上下文中执行,其中 ReportImpl
类将在应用程序上下文中。有没有办法获取 reppropname
.
我尝试使用 @ContextConfiguration (@ContextConfiguration(classes={ApplicaitonBootStarter.class)}
它正在工作,但它加载了所有 bean 和依赖项。
还有其他方法可以获取reppropname吗?
最佳答案
此处未注入(inject)值的原因是您没有向测试类提供配置。 Spring 只是不知道如何构建你的 bean。
因此,正如您所提到的,您必须使用 @ContextConfiguration
注释测试类。如果您不想使用所有 bean 构建整个上下文,您可以创建一个测试配置并仅提供所需的 bean。
@Configuration //can be as well annotated with @TestConfiguration
@ComponentScan("package.to.scan")
public class TestConfiguration {
}
现在将此类提供给您的测试
@RunWith(SpringRunner.class)
@TestPropertySource("classpath:application-test.properties")
@ContextConfiguration(classes = TestConfiguration.class)
public class ReportImplTest {
........
}
但是还有一件事。假设您有一个执行 MockitAnnotations.initMocks(this);
的 @Before
方法,您仍然仅使用 @InjectMocks< 声明被测对象
。这是什么意思?这意味着如果你不自己初始化这个对象,mockito会处理它并使用可用的构造函数进行初始化,在这种情况下,spring不会注入(inject)@Value注释 field 。你需要做的是用@Autowired注释你的被测对象,这样spring会在mockito尝试处理它之前初始化它:
@InjectMocks
@Autowired
private ReportImplTest underTest;
关于java - 使用 @value 注释将属性字段传递给模拟方法为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53137644/