如何 运行 正确的 phpunit 测试文件,在生产代码中,使用 vim 命令

How to run right phpunit test file, when in production code, with vim command

我现在已经映射了一个快捷方式,因此我可以运行 php 当前测试文件。当我开发时,我将我的 window 分成两部分:一方面我保留测试,另一方面我保留生产代码。如果我在测试文件上,感谢

:map <leader>t :!vendor/bin/phpunit %<cr>

我可以 运行 当前 phpunit 测试。 %代表当前文件。我希望能够 运行 一个测试文件,当我使用生产代码时也是如此。示例:

 - src/Foo/Bar/ProductionCode.php
 - test/Foo/Bar/ProductionCodeTest.php

我可以映射

<leader>t

以便我可以 运行 从 ProdutionCode.php 进行测试?我每次需要做的是Ctrl+w Ctrl+w <leader>t。我只想 运行 <leader>t 命令。有人可以帮助我吗?

测试的命名空间反映了生产的命名空间。我认为一个好主意可能是

:map <leader>t :!vendor/bin/phpunit TESTFILE<cr>

其中 TESTFILE 类似于此伪代码:

if current file ends with Test.php
    return %
else
    fileName = % " src/Foo/Bar/ProductionCode.php
                 " src/Foo/Bar/ProductionCodeTest.php
                 " test/Foo/Bar/ProductionCodeTest.php
    return fileName
endif

有可能吗?

function! RunPhpUnit()
    let l:filename = expand('%')
    if l:filename !~# 'Test\.php$'
        let l:filename=substitute(l:filename, '\.php$', 'Test.php', '')
    endif
    let l:filename=substitute(l:filename, 'code\/classes', 'spec\/unit', '')
    return ':!vendor/bin/phpunit ' . l:filename . "\<CR>"
endfunction
:noremap <expr> <leader>t RunPhpUnit()

是的,这是可以做到的。对于文件名中的简单替换,您可以使用 :help filename-modifiers 下列出的修饰符,例如将 src 变为 test:

:noremap <leader>t :!vendor/bin/phpunit %:s?src?test?<cr>

对于更复杂的逻辑(看起来你需要那个),你可以使用 :help :map-expression 然后使用条件来处理文件名:

function! RunPhpUnit()
    let l:filename = expand('%')
    if l:filename !~# 'Test\.php$'
        call substitute(l:filename, '\.php$', 'Test.php', '')
    endif
    call substitute(l:filename, 'src', 'test', '')
    return ':!vendor/bin/phpunit ' . l:filename . "\<CR>"
endfunction
:noremap <expr> <leader>t RunPhpUnit()

PS: You should use :noremap;它使映射不受重新映射和递归的影响。