【问题标题】:Mock prototype scoped bean模拟原型作用域bean
【发布时间】:2018-10-01 18:37:11
【问题描述】:

我有两个豆子:

@Component
public class StudentServices {

    // ... member variables, etc.

    @Lookup
    public SchoolNotification getNotification() {
        return null;
    }

    // ... getters and setters
}

还有第二个豆子:

@Component
@Scope("prototype")
public class SchoolNotification {
    // ... prototype-scoped state
}

我需要帮助来为 StudentServices 编写一个单元测试,以某种方式模拟 SchoolNotification。

Mockito.mock 不起作用,因为这两个 bean 具有不同的范围,并且每次执行 StudentServices.getNotification() 时,spring 上下文都会提供一个新的 SchoolNotification 实例。

任何帮助将不胜感激!

【问题讨论】:

    标签: spring unit-testing spring-boot mockito


    【解决方案1】:

    为了回答我自己的问题,这是通过间谍解决的。

    类似这样的:

    @组件 公共类 StudentServicesTest {

    @Mock
    SchoolNotification schoolNotification; 
    @Spy
    @InjectMock
    private StudentServices studentServices;
    
    
    @Before
    public void setUp(){
       doReturn(null).when(studentServices).getSchoolNotification();
       //If you want to return something else then
      doReturn(schoolNotification).when(studentServices).getSchoolNotification();
    }
    
    @Test
    public void testOtherMethods(){
        //Prepare other when/doReturs/etc
        //Test other method using studentServices
        //list of assertions
    }
    

    }

    【讨论】:

    • @user1767316 当然,我编辑了我的回复以显示我当时使用的代码。让我知道它是否有效。
    • 谢谢@user1532449,我会看看它是否对我有帮助,我相信你的代码会帮助那些坚持测试和理解你的答案的人。我在我的代码中使用了“@SpyBean”,不使用“@InjectMock”我会看看它
    猜你喜欢
    • 2018-03-20
    • 2019-06-06
    • 2019-07-24
    • 2015-11-26
    • 1970-01-01
    • 2021-01-13
    • 2015-01-14
    • 2013-08-05
    • 1970-01-01
    相关资源
    最近更新 更多