热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

单元测试JSR-330注入的对象-UnittestingJSR-330injectedobjects

IhavepreviouslyusedSpringDI,andoneofthebenefitsIperceiveisthatIcantestmySpringbe

I have previously used Spring DI, and one of the benefits I perceive is that I can test my Spring bean classes without involving Spring (imports omitted for brevity):

我以前使用过Spring DI,我认为其中一个好处是我可以在不涉及Spring的情况下测试我的Spring bean类(为简洁起见省略了导入):

public class Foo {
    private String field;

    public void setField(String field) { this.field = field; }
    public String getField() { return field; }
} 

public class TestFoo {
    @Test
    public void test_field_is_set() {
       Foo foo = new Foo();
       foo.setField("Bar");
       assertEquals("Bar", foo.getField());
    }
}

Now I am experimenting with JSR-330, which means not explicitly writing setters.

现在我正在尝试使用JSR-330,这意味着没有明确地编写setter。

I'm using Hk2 so far, purely because of some anecdotal stuff about Jersey being tied to Hk2, and making it difficult to co-habit with other JSR-330 implementations.

到目前为止,我正在使用Hk2,纯粹是因为有些关于Jersey与Hk2绑定的传闻,并且难以与其他JSR-330实现共存。

public class Foo {
   @Inject 
   private String field;
}

I half expected some magic to happen, whereby the @Inject annotation caused a setter to become available, but this is not the case:

我有一半期望发生一些魔法,因此@Inject注释导致一个setter变得可用,但事实并非如此:

Foo foo = new Foo();
foo.setField("Bar"); // method setField(String) is undefined for the type Foo
  • How can I (conveniently) test this kind of annotated class without invoking a framework?
  • 如何在不调用框架的情况下(方便地)测试这种带注释的类?
  • Failing that, how can I invoke a framework in a portable way (i.e. without tightly coupling my test code to Hk2, Guice, etc.)
  • 如果做不到这一点,我怎么能以便携方式调用框架(即没有将我的测试代码紧密耦合到Hk2,Guice等)
  • Failing that, what's a typical, clean way to test classes annotated in this way?
  • 如果做不到这一点,以这种方式测试类的典型,干净的方法是什么?

4 个解决方案

#1


2  

Simplest is to make the fields package-private (instead of private), then in the test, set them directly. (That works if the test is in the same package)

最简单的方法是使字段package-private(而不是private),然后在测试中直接设置它们。 (如果测试在同一个包中,则有效)

public class Foo {
   @Inject 
   String field;
}



Foo foo = new Foo();
foo.field = "bar";

This has the advantage of avoiding reflection so it's safe for refactoring.

这具有避免反射的优点,因此可以安全地进行重构。

#2


1  

The field injection approach you mentioned is actually the typical Spring style; many programmers don't write setters for private injected fields at all. Spring (with @Autowired or @Inject) and JSR-330 containers usually inject fields using direct field reflection rather than setters.

你提到的现场注入方法实际上是典型的Spring风格;许多程序员根本没有为私有注入字段编写setter。 Spring(使用@Autowired或@Inject)和JSR-330容器通常使用直接场反射而不是setter来注入字段。

Because of this, if you don't want to use any DI framework, you could write the necessary reflection code into your unit tests yourself, but this seems like overkill just to avoid a test dependency; after all, the point of using @Inject is that you're coding to an interface, and you don't avoid using the JVM to avoid coupling to it.

因此,如果你不想使用任何DI框架,你可以自己在单元测试中编写必要的反射代码,但这似乎有点过分以避免测试依赖;毕竟,使用@Inject的关键在于您正在编写接口,并且不要避免使用JVM来避免与它耦合。

The usual approach for testing this sort of class is to set up a test context for whatever container you prefer and run the unit tests in that context. If you're using Spring, you'd put an applicationContext-test.xml file or TestConfig class in your src/test/ directory (or equivalent), and if you're using Guice, you'd write a module to wire up mocks or test datasets.

测试此类类的常用方法是为您喜欢的任何容器设置测试上下文,并在该上下文中运行单元测试。如果您正在使用Spring,那么您需要在src / test /目录(或等效的)中放置applicationContext-test.xml文件或TestConfig类,如果您使用的是Guice,则需要编写一个模块来连接模拟或测试数据集。

#3


1  

It turns out that frameworks relying on private/protected field access are not so uncommon. Hibernate, JPA, several JSR-330 implementations, including Spring itself, all do it.

事实证明,依赖私有/受保护的字段访问的框架并不是那么罕见。 Hibernate,JPA,几个JSR-330实现,包括Spring本身,都做到了。

Spring's spring-test package provides a ReflectionTestUtils class containing static methods for accessing these fields.

Spring的spring-test包提供了一个ReflectionTestUtils类,其中包含用于访问这些字段的静态方法。

Using this one can test the class in the question thus:

使用这个可以测试问题中的类:

import static org.springframework.test.util.ReflectionTestUtils.*;

...

@Test
public void testUsingSpringReflectionTestUtils() {
    Foo foo = new Foo();
    setField(foo, "field", "Bar");
    assertEquals("Bar", foo.getField());
}

You need spring-test and spring-core in your test classpath for this to work, but it doesn't add a dependency on Spring for your production code.

您需要在测试类路径中使用spring-test和spring-core才能使用它,但它不会为您的生产代码添加Spring依赖性。

(Comments welcome about alternative implementations of the same principle welcome. I don't think it's worth rolling one's own, however simple it would be, given that Spring has a good implementation.)

(评论欢迎关于相同原则欢迎的替代实现。我认为不值得推出自己的,不管它是多么简单,因为Spring有一个很好的实现。)

#4


1  

Give "needle" a try: http://needle.spree.de/overview

试试“针”:http://needle.spree.de/overview

needle is an DI-test-framework that only simulates the container behavior, making unit tests real simple.

needle是一个DI测试框架,只模拟容器行为,使单元测试变得非常简单。


推荐阅读
  • 本文主要解析了Open judge C16H问题中涉及到的Magical Balls的快速幂和逆元算法,并给出了问题的解析和解决方法。详细介绍了问题的背景和规则,并给出了相应的算法解析和实现步骤。通过本文的解析,读者可以更好地理解和解决Open judge C16H问题中的Magical Balls部分。 ... [详细]
  • Spring特性实现接口多类的动态调用详解
    本文详细介绍了如何使用Spring特性实现接口多类的动态调用。通过对Spring IoC容器的基础类BeanFactory和ApplicationContext的介绍,以及getBeansOfType方法的应用,解决了在实际工作中遇到的接口及多个实现类的问题。同时,文章还提到了SPI使用的不便之处,并介绍了借助ApplicationContext实现需求的方法。阅读本文,你将了解到Spring特性的实现原理和实际应用方式。 ... [详细]
  • 自动轮播,反转播放的ViewPagerAdapter的使用方法和效果展示
    本文介绍了如何使用自动轮播、反转播放的ViewPagerAdapter,并展示了其效果。该ViewPagerAdapter支持无限循环、触摸暂停、切换缩放等功能。同时提供了使用GIF.gif的示例和github地址。通过LoopFragmentPagerAdapter类的getActualCount、getActualItem和getActualPagerTitle方法可以实现自定义的循环效果和标题展示。 ... [详细]
  • 先看官方文档TheJavaTutorialshavebeenwrittenforJDK8.Examplesandpracticesdescribedinthispagedontta ... [详细]
  • 本文讨论了在VMWARE5.1的虚拟服务器Windows Server 2008R2上安装oracle 10g客户端时出现的问题,并提供了解决方法。错误日志显示了异常访问违例,通过分析日志中的问题帧,找到了解决问题的线索。文章详细介绍了解决方法,帮助读者顺利安装oracle 10g客户端。 ... [详细]
  • Thisworkcameoutofthediscussioninhttps://github.com/typesafehub/config/issues/272 ... [详细]
  • 在Android开发中,使用Picasso库可以实现对网络图片的等比例缩放。本文介绍了使用Picasso库进行图片缩放的方法,并提供了具体的代码实现。通过获取图片的宽高,计算目标宽度和高度,并创建新图实现等比例缩放。 ... [详细]
  • 本文介绍了在CentOS上安装Python2.7.2的详细步骤,包括下载、解压、编译和安装等操作。同时提供了一些注意事项,以及测试安装是否成功的方法。 ... [详细]
  • MPLS VP恩 后门链路shamlink实验及配置步骤
    本文介绍了MPLS VP恩 后门链路shamlink的实验步骤及配置过程,包括拓扑、CE1、PE1、P1、P2、PE2和CE2的配置。详细讲解了shamlink实验的目的和操作步骤,帮助读者理解和实践该技术。 ... [详细]
  • 本文由编程笔记#小编整理,主要介绍了关于数论相关的知识,包括数论的算法和百度百科的链接。文章还介绍了欧几里得算法、辗转相除法、gcd、lcm和扩展欧几里得算法的使用方法。此外,文章还提到了数论在求解不定方程、模线性方程和乘法逆元方面的应用。摘要长度:184字。 ... [详细]
  • 合并列值-合并为一列问题需求:createtabletab(Aint,Bint,Cint)inserttabselect1,2,3unionallsel ... [详细]
  • Java 11相对于Java 8,OptaPlanner性能提升有多大?
    本文通过基准测试比较了Java 11和Java 8对OptaPlanner的性能提升。测试结果表明,在相同的硬件环境下,Java 11相对于Java 8在垃圾回收方面表现更好,从而提升了OptaPlanner的性能。 ... [详细]
  • 本文介绍了如何在Jquery中通过元素的样式值获取元素,并将其赋值给一个变量。提供了5种解决方案供参考。 ... [详细]
  • 本文介绍了利用ARMA模型对平稳非白噪声序列进行建模的步骤及代码实现。首先对观察值序列进行样本自相关系数和样本偏自相关系数的计算,然后根据这些系数的性质选择适当的ARMA模型进行拟合,并估计模型中的位置参数。接着进行模型的有效性检验,如果不通过则重新选择模型再拟合,如果通过则进行模型优化。最后利用拟合模型预测序列的未来走势。文章还介绍了绘制时序图、平稳性检验、白噪声检验、确定ARMA阶数和预测未来走势的代码实现。 ... [详细]
  • Answer:Theterm“backslash”isonofthemostincorrectlyusedtermsincomputing.People ... [详细]
author-avatar
可怜的绷带_565
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有