php-school / cli-menu

🖥 Build beautiful PHP CLI menus. Simple yet Powerful. Expressive DSL.
http://www.phpschool.io
MIT License
1.94k stars 107 forks source link

PHPUnit problem if first item is not a SelectableItem which calls ->close() #262

Closed Zerogiven closed 2 years ago

Zerogiven commented 2 years ago

Hi,

First of all thanks for the great work :)

Could you tell me why it is neccessary for phpunit to have a selectable item at first which closing the menu?

Cause this makes it a bit harder for me to test my class with your cli-menu implementation cause i am generating the menu items and i would like to test if it generates the correct items. Only for this reason i would have to make a tiny hack where i can add an extra item at first position before my generated items.

Maybe you have an idea if or how i could test it without having the SelectableItem with menu->close().

You can reproduce it in your tests for example at:

    public function testSimpleOpenClose() : void
    {
        $this->terminal->expects($this->any()) // changed from $this->once() to $this->any()
            ->method('read')
            ->willReturn("\n");

        $style = $this->getStyle($this->terminal);

        $item = new SelectableItem('Item 1', function (CliMenu $menu) {
            // $menu->close(); // If this is in all works fine
        });

        $menu = new CliMenu('PHP School FTW', [$item], $this->terminal, $style);
        $menu->open();

        self::assertStringEqualsFile($this->getTestFile(), $this->output->fetch());
    }

it looks like phpunit then stucks inside an endless loop, but had not enough time yet to debug it

AydinHassan commented 2 years ago

That's how it works: CliMenu runs in an infinite loop waiting for input. In this example, the test, testSimpleOpenClose - we have one item in the menu, that when selected, will close the menu. We simulate an enter key press which triggers the action of the menu item and closes the menu.

CliMenu only executes code (actions) when items are selected. If no item is selected then no code can run and the menu cannot be closed.

If you want to check the items, don't call open (which starts the loop) and call getItems and check them that way.

Does that help?

Zerogiven commented 2 years ago

Ahhh got it, sorry i had a misconception about the read mocking method :roll_eyes: thanks anyway! now i know how i'll do it ;)