不同的bean服务的春季测试

时间:2015-05-04 06:52:53

标签: java spring

我想测试服务A,它有方法methodA1,A指的是服务B,它有方法methodB1,

在methodA1中调用methodB1,

@Service
class A{
    @Autowired
    B b;
    void methodA1{
      ....
      b.methodB1();
      .....
    }
}

@Service
class B{

    void methodB1{
      ....
    }
}

现在,我想测试methodA1,但是需要重写methodB1,所以我创建了一个新类BMock;

@Service("bMock")
class BMock execute B{
    @Override
    void methodB1{
    ....
    }
}

这样的测试用例:

class testClass extends springTest{

    @Autowired
    A a;

    @Autowired
    @Qualifier("bMock")
    B b;

    @Test
    public void testMethodA1(){
        a.methodA1();
    }
}

实际上,methodA1总是在B类中调用methodB1,我希望它在测试用例中调用BMock,该怎么做?

2 个答案:

答案 0 :(得分:0)

Spring Re-Inject可用于在测试环境中用模拟替换bean。

 @ContextConfiguration(classes = {ReInjectContext.class, testClass.TextContext.class})
 class testClass extends springTest {
    @Autowired
    A a;

    // Spring context has a bean definition for B, but it is     
    // overridden in the test's constructor, so BMock is created
    // instead of B. BMock gets injected everywhere, including A and the 
    // test
    @Autowired
    B b; 
    public testClass() {
           // Replace bean with id "b" with another class in constructor
           // "b" is bean ID that Spring assigns to B 
           ReInjectPostProcessor.inject("b", BMock.class);
    }

   @Test
   public void testMethodA1(){
      a.methodA1();
   }

    // If A and B are already the part of Spring context, this config
    // is not needed
    @Configuration
    static class TestContext   {
        @Bean public A a() {  return new A(); }
        @Bean public B b() {  return new B(); }
    }
 }

从BMock中删除@Qualifier和@Service

答案 1 :(得分:0)

如果您在A类中有/path/to/spark/sbin/start-history-server.sh /path/to/event-log的setter,请在test中明确覆盖它:

b

如果您没有设置器(并且不想创建它),则可以使用反射:

class testClass extends springTest{

    @Autowired
    A a;

    @Autowired
    @Qualifier("bMock")
    B b;

    @Test
    public void testMethodA1(){
        a.setB(b);
        a.methodA1();
    }
}

它打破了私有字段的隔离,但可能可以接受测试。