使用Junit和EasyMock使用自动装配的符号对类进行单元测试? [英] Unit testing a class with autowired notation using Junit and EasyMock?

查看:126
本文介绍了使用Junit和EasyMock使用自动装配的符号对类进行单元测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为一个类的单元测试编写一个单元测试,该类的多个字段标记为@Autowired.鉴于Spring会自动解决这些字段的具体实现这一事实,我很难弄清楚如何在测试运行期间将我的Mock对象(通过EasyMock创建)作为依赖项插入.在该类中使用@Autowired意味着该类中没有设置器.有没有办法让我的模拟对象插入而无需在类中创建其他设置器?

I am trying to write a Unit test for a class that has several of its fields marked @Autowired. Given the fact that Spring is automatically resolving the concrete implementations for these fields, I am having a hard time figuring out how to plug my Mock objects(created via EasyMock) as the dependencies during the test-run. Using @Autowired in the class means lack of setters in that class. Is there a way for me to plug my mock objects in without creating additional setters in class?

这是我要完成的工作的一个示例:

Here's an example of what I am trying to accomplish:

public class SomeClassUnderTest implements SomeOtherClass{

@Autowired
private SomeType someType;

@Autowired
private SomeOtherType someOtherType;

@Override
public SomeReturnType someMethodIWouldLikeToTest(){
//Uses someType and someOtherType and returns SomeReturnType
}

}

这是我碰壁之前如何制作Test类的方法:

Here's how I am crafting my Test class before I hit the wall:

public class MyTestClassForSomeClassUnderTest{
  private SomeType someType;
  private SomeOtherType someOtherType;

  @Before
  public void testSetUp(){
    SomeClassUnderTest someClassToTest = new SomeClassUnderTest();
    someType = EasyMock.createMock(SomeType.class);
    someOtherType = EasyMock.createMock(SomeOtherType.class);
    //How to set dependencies????
  }

  @Test
  public void TestSomeMethodIWouldLikeToTest(){
    //??????
  } 

}

最好朝正确的方向前进.

It will be great to get a push in the right direction.

谢谢

推荐答案

您可以使用

You can reflectively inject dependencies directly into the field using ReflectionTestUtils, e.g.

ReflectionTestUtils.setField( testInstance, "fieldName", fieldValue );

有些人认为最好还是将包可见的setter方法添加到类中,仅由测试使用.另外,可以使用自动装配的构造函数,而不要使用自动装配的字段,然后将测试依赖项注入其中.

Some would argue that it's preferable to add a package-visible setter method to the class anyway, used solely by the tests. Alternatively, use autowired constructors, rather than autowired fields, and inject the test dependencies into that.

这篇关于使用Junit和EasyMock使用自动装配的符号对类进行单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆