模拟服务未返回true,始终返回false

问题描述 投票:1回答:1

下面的代码(CallService.java)调用一个称为AService的服务,并进行一些更新,然后返回一个布尔值。

    public boolean getUpdateStatus() throws ServiceException {
    if (finder == null) {
        finderBean = new FinderBean();
    }
    myService = finderBean.find(AService.class);
    if (myService == null) {
        System.out.println("null >>>>>>>");
    }

    final Config config = new Config();
    final Update update = new Update();
    status = myService.update(update, config);
    System.out.println("Status: " + status);
    return status;
}

下面的测试用例将验证CallService.java;已经模拟了所有与服务相关的类,并调用了我的受测类以调用AService并声明了bolean,但无论模拟如何,模拟总是返回false。

@Before
public void setUp() throws Exception {

    myService = PowerMockito.mock(AService.class);
    finderBean = PowerMockito.mock(FinderBean.class);

    update = PowerMockito.mock(Update.class);
    config = PowerMockito.mock(Config.class);       
PowerMockito.whenNew(FinderBean.class).withNoArguments().thenReturn(finderBean);

PowerMockito.when(finderBean.find(AService.class)).thenReturn(myService);
}

@Test
public void TestUpdateState() throws Exception {

    callService = new CallService();
    MemberModifier.field(CallService.class, "finderBean").set(callService, finderBean);
    PowerMockito.when(finderBean.find(AService.class)).thenReturn(myService);
    PowerMockito.when(myService.update(update, config)).thenReturn(true);

    final boolean status = callService.getUpdateStatus();
    assertTrue(status);
}

我是否在这里缺少任何指针?

谢谢。

mocking mockito powermock
1个回答
1
投票

根据documentation

所有用法都需要@RunWith(PowerMockRunner.class)@PrepareForTest 在类级别上注释

例如,使用PowerMockito。在新增时使用

whenNew(MyClass.class).withNoArguments().thenThrow(new IOException("error message"));

请注意,您必须为创建MyClass的新实例(而不是MyClass本身)的类做好准备。例如。如果将执行new MyClass()的类称为X,则必须执行@PrepareForTest(X.class)才能使whenNew工作:

我的重点

因此请确保您具有必要的属性,并相应地模拟了依赖项

@RunWith(PowerMockRunner.class)
@PrepareForTest(CallService.class)
public class TestMyClass {
    FinderBean finderBean;
    AService myService;

    @Before
    public void setUp() throws Exception {        
        myService = PowerMockito.mock(AService.class);
        finderBean = PowerMockito.mock(FinderBean.class);
        PowerMockito.whenNew(FinderBean.class).withNoArguments().thenReturn(finderBean);            
    }

    @Test
    public void TestUpdateState() throws Exception {
        //Arrange                      
        PowerMockito.when(finderBean.find(AService.class)).thenReturn(myService);
        PowerMockito.when(myService.update(any(Update.class), any(Config.class))).thenReturn(true);
        CallService callService = new CallService(); 

        //Act
        final boolean status = callService.getUpdateStatus();

        //Assert
        assertTrue(status);
    }
}

之所以无法与您的模拟服务一起使用,是因为测试中的参数与被测方法中的参数不同。被测试方法正在本地创建自己的实例,这意味着它们将与测试设置中使用的实例不同,因此在调用时不会表现出预期的行为。

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.