我有一个正在测试其他类方法的测试类

其他班级的结构是这样的

@Component
public abstract class ParentOpManager{
     @Autowired
     private ProcessorRequestWrapper processorRequestWrapper;

     @Autowired
     private XYProcessor xyProcessor;

}

@Component("childManager")
public class ChildOperationManager extends ParentOpManager{

}

public abstract class ParentClass{
       protected final RequestWrapper requestWrapper;
       protected final ParentOpManager parentOpManager;


       public ParentClass(final RequestWrapper requestWrapper, final ParentOpManager parentOpManager){
           this.requestWrapper = requestWrapper;
           this.parentOpManager = parentOpManager;
       }
}


我还有,孩子班扩大了这个班

public class ChildClass extends ParentClass{

      @Autowired
      private NinjaManager ninjaManager;

      @Autowired
      public ChildClass(final RequestWrapper requestWrapper, @Qualifier("childManager")final ParentOpManager parentOpManager){
          super(requestWrapper, parentOpManager);
      }

      public void methodA() throws Exception {
          Request item = requestWrapper.findItem(); // Problem place 1
      }

      public void methodB() throws Exception {
          Request item = ninjaManager.findItem(); // Problem place 2
      }
}


我需要测试ChildClass的方法。为此,我编写了一个测试班。

//@RunWith(MockitoJunitRunner.class)
//@ContextConfiguration
public class TestClass{

    @Mock
    ChildOperationManager chOpManager;

    @Mock
    RequestWrapper requestWrapper;

    @InjectMocks
    ChildClass childObject;

    @Before
    public void setup(){
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void testSomeMethodA() throws Exception{
        childObject.methodA();
    }
}


所以,问题是当我是测试类的methodA类时,requestWrapper为NULL。我不明白为什么会这样?

编辑:

如果我喜欢

    @Mock
    ChildOperationManager chOpManager = new ChildOperationManager();

    @Mock
    RequestWrapper requestWrapper;

    @InjectMocks
    ChildClass childObject = new childObject(requestWrapper, chOpManager);


问题接缝有待解决。还有其他问题,可能是一些权限问题。但是您认为这样做是一种好方法吗?

最佳答案

您的错误是这样的:

@Autowired
public ChildClass(final RequestWrapper requestWrapper, @Qualifier("childManager")final ParentOpManager parentOpManager){
    super(requestWrapper, parentOpManager);
}

public void methodA() throws Exception {
    Request item = requestWrapper.findItem(); // this requestWrapper is null
}


您没有在子级中分配requestWrapper引用。因此它保持为空。

您应该只从子级中删除成员变量requestWrapperparentOpManager。这样,您将使用父级的已初始化的。

07-24 09:26