2015-05-04 101 views
0

我想测试的服务A,其具有方法methodA1,A指的是一个服务B,其具有方法methodB1,与差豆服务弹簧测试

在methodB1被称为在methodA1,

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

@Service 
class B{ 

    void methodB1{ 
     .... 
    } 
} 

现在,我想测试methodA1,但方法B1需要重写,所以我创建了一个新的类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随时调用methodB1在B类,我想它来调用BMock测试的情况下,该怎么办呢?

+0

为什么不使用easymock/powermock/mockito等模拟框架? – SMA

+0

'@Qualifier(“bMock”)'在这种情况下不会做任何事情(AFAIK)。你的界面。而不是concreate'B使用'AnInterfaceThatBImplements b' – Shahzeb

+0

@Shahzeb,你的意思是我需要创建一个接口Ib,B类和BMock实现接口Ib?如果这样,bMock可以在测试用例中调用吗? – Mike

回答

0

Spring Re-Inject可用于在测试环境中用mocks代替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

0

删除@Qualifier和@Service如果你有一个设置为A类b,明确地将其覆盖在测试:

class testClass extends springTest{ 

    @Autowired 
    A a; 

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

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

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

Field bField = A.getDeclaredField("b"); 
fField.setAccessible(true); 
fField.set(a, b); 

它打破私人领域的兴起,但对于测试可能是可以接受的。