简体   繁体   English

测试 class 字段,方法之间共享

[英]Testing for class field with is share among methods

I have a Java class as follow我有一个 Java class 如下

public class MyClass {
    private final ShowFactory showFactory;
    private SomeShow someShow;

    public MyClass(ShowFactory showFactory) {
        this.showFactory = showFactory;
        startShow();
    }

    public void startShow() {
        someShow = showFactory.createShow();
        someShow.start();
    }

    public void showSomething() {
        MagicBox magicBox = new MagicBox();
        someShow.showSomething(magicBox);
    }

    public void stopShow() {
        someShow.stop();
    }
}

and trying to test showSomething method.并尝试测试showSomething方法。 Complete test file is as follow完整的测试文件如下

public class MyClassTest {
    private ShowFactory showFactory;
    private SomeShow someShow;

    @Before
    public void setUp() {
        showFactory = mock(ShowFactory.class);
        someShow = mock(SomeShow.class);

        when(showFactory.createShow()).thenReturn(someShow);
    }

    @Test
    public void shouldStartShow() {
        new MyClass(showFactory);

        verify(someShow).start();
    }

    @Test
    public void shouldShowSomething() throws Exception {
        MagicBox magicBox = mock(MagicBox.class);
        PowerMockito.whenNew(MagicBox.class).withAnyArguments().thenReturn(magicBox);
        doNothing().when(someShow).showSomething(magicBox);
        InOrder inOrder = inOrder(someShow);

        MyClass myClass = new MyClass(showFactory);
        myClass.showSomething();

        inOrder.verify(someShow).start();
        inOrder.verify(someShow).showSomething(magicBox);
    }

    @Test
    public void shouldStopShow() {
        MyClass myClass = new MyClass(showFactory);
        myClass.stopShow();

        verify(someShow).start();
        verify(someShow).stop();
    }
}

But test shouldShowSomething is failing with error Wanted but not invoked .但是测试shouldShowSomething失败并出现错误Wanted but not invoked invoked 。 Any thing I am missing here?我在这里缺少什么吗? Any suggestion?有什么建议吗?

It was simple fix.这是简单的修复。 After reading through https://github.com/powermock/powermock/wiki/MockConstructor#quick-summary (thanks to @roby) turns out I was missing the @PrepareForTest annotation for the class.通读https://github.com/powermock/powermock/wiki/MockConstructor#quick-summary (感谢@roby)后发现我错过了 class 的@PrepareForTest注释。

@RunWith(PowerMockRunner.class)
@PrepareForTest(MyClass.class)
public class MyClassTest {
 ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM