【问题标题】:How to test this method by JUnit & EasyMock?如何通过 JUnit & EasyMock 测试这个方法?
【发布时间】:2016-05-12 16:03:52
【问题描述】:

我有一个

@Component
public class MyBean{

         @Autowired
         Bean1 bean1;

         @Autowired
         Bean2 bean2;

         public void create(Param param1, Param param2){
           SomeObject object =    bean2.getDesiredResult();
         }

}

其中Bean2.javainstance variablesautowired-

class Bean2{
    @Autowired
    Bean3 bean3;

    @Autowired
    Bean4 bean4;

    @Autowired
    Bean5 bean5;

    public Object getDesiredResult(){
        // some code which calls method on some beans which have autowired
        // beans, and this goes on and on further.
    }

}

我得测试一下这个方法,

create(Param param1, Param param2)

主要问题是我继续得到这些异常:

没有符合条件的 bean 类型
无法自动装配字段

因为我不能手动 component-scan 所有的包,因为它们的数量太大了。项目中有大约 3000 个 java 包

<context:component-scan base-package

我正在使用JUnitEasyMock 框架。 请提出建议。

【问题讨论】:

    标签: spring-mvc junit4 easymock


    【解决方案1】:

    你似乎混合了两件事。您想使用 JUnit 和 EasyMock 进行单元测试。这不需要 Spring 或任何自动装配。您将执行以下操作:

    // Record the mock
    Bean2 mock = createMock(Bean2.class);
    expect(mock.getDesiredResult()).andReturn(new SomeObject());
    replay(mock);
    
    // Configure the tested class
    MyBean testSubject = new MyBean();
    testSubject.setBean(mock);
    
    // Test
    testSubject.create(new Param1(), new Param2());
    
    // Check the mock was called as expected
    verify(mock);
    

    用于包裹扫描。从我的角度来看,这与测试无关,包扫描可以是递归的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-07-08
      • 1970-01-01
      • 2012-07-14
      • 2016-07-20
      • 2012-07-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多