【问题标题】:Mock an object which is part of mocked object模拟作为模拟对象一部分的对象
【发布时间】:2017-06-07 09:17:22
【问题描述】:

当我运行测试用例时,我得到了 AnObj 的嘲笑。这是从目标类方法内部使用的。当该方法被调用时,“anOtherObj”被访问并且被发现为空。有人可以指出如何确保“anOtherObj”不为空,这样我就不会在那里得到空指针吗?

    @Test
    public class TestTargetTest {

    @Mock
    private AnObj anObj;

    @InjectMocks
    private TestTarget testTarget;

    @BeforeMethod
    public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void testTarget() {

        when(anObj.someMethod()).thenCallRealMethod();

        testTarget.testTarget();



    }

}

@Component
public class TestTarget {

    @Autowired
    private AnObj anObj;

    public void testTarget(){

        anObj.someMethod();
    }
}

@Component
public class AnObj {

    @Autowired
    private AnOtherObj anOtherObj;

    public void someMethod(){
        syso(anOtherObj.toString());
    }
}

【问题讨论】:

  • 什么是mirrorIbpCusUserRepository?
  • 这将确保“anOtherObj.toString()”被成功调用。

标签: spring mockito testng


【解决方案1】:

您需要在测试类中初始化带注释的模拟。

@BeforeMethod
public void beforeClass() {
    MockitoAnnotations.initMocks(this);
}

【讨论】:

  • 感谢您指出......但问题比错过这个更深。这个功能我在实际课堂上拥有,但为简洁起见未能在此处发布。我现在发布答案。感谢您的帮助
【解决方案2】:

您为什么要关心 mock (AnObj) 内部的内容?我假设您尚未使用 Mockito.when 在该模拟上声明交互。

【讨论】:

  • 当我们谈论 AnObj.someMethod() 时,你是对的。我要么模拟这个方法,要么调用真正的方法。我叫真人。当真正的方法被调用访问类成员时。
【解决方案3】:

正如@Valya 所提到的,这一点是有效的。我不应该嘲笑那个。我需要自动装配“AnObj”。非常感谢所有的帮助。它有所作为。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-15
    • 1970-01-01
    • 2017-04-07
    • 1970-01-01
    相关资源
    最近更新 更多