有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

使用差分bean服务的JavaSpring测试

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

在methodB1中,在methodA1中调用

@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) 个答案

  1. # 1 楼答案

    如果在类a中有b的setter,请在测试中明确重写它:

    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);
    

    它打破了私人领域的隔离,但可能可以接受测试

  2. # 2 楼答案

    Spring Re-Inject可以用来在测试环境中用mock替换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