2017-04-05 103 views
6

有沒有辦法在doctests中使用模塊別名?我不想每次都輸入一個長名字。Elixir - 如何在doctest中使用別名?

defmodule SomeLongModuleName.SubModule do 
    alias SomeLongModuleName.SubModule, as: SubModule 

    @doc """ 
     iex> SubModule.method(%{property_a: 1, property_b: 2) # CompileError 
     3 
    """ 
    def method(%{property_a: a, property_b: b) do 
    a + b 
    end 
end 

上面的例子顯示了我可能想要使用別名來避免長行的情況。是否可以在doctest中使用別名?

+0

我假設文檔測試從全球運行命名空間,所以它將無法看到別名。 – Dylanthepiguy

回答

11

有兩種方法我可以想到不必一次又一次鍵入模塊名稱。

  1. 使用插在你的文檔和使用別名名稱:

    defmodule SomeLongModuleName.SubModule do 
        alias SomeLongModuleName.SubModule, as: SubModule 
    
        @doc """ 
         iex> #{SubModule}.method(%{property_a: 1, property_b: 2}) 
         3 
        """ 
        def method(%{property_a: a, property_b: b}) do 
        a + b 
        end 
    end 
    
  2. 使用只是沒有模塊和您的來電doctest從測試中的功能名稱,添加import: true

    defmodule SomeLongModuleName.SubModule do 
        @doc """ 
         iex> method(%{property_a: 1, property_b: 2}) 
         3 
        """ 
        def method(%{property_a: a, property_b: b}) do 
        a + b 
        end 
    end 
    
    doctest SomeLongModuleName.SubModule, import: true 
    
+1

不錯!第一個選項看起來像一個(相當整潔的)黑客,第二個選項看起來就像它是爲這種情況準備的。也許切換順序? – Dylanthepiguy

+0

選項2像一個魅力工作:)謝謝。 – PlagueHammer

1

事實證明,您可以在測試之前放置一條alias SomeLongModuleName.SubModule, as: SubModule行。

更好的解決方案是不要在文檔中放置太多測試,也不要使用別名。然後,在您的測試文件中,您可以將alias SomeLongModuleName.SubModule, as: SubModule保存。

1

正如dylanthepiguy所提到的,將別名放入測試文件中,在doctest行之前,絕對是一個更好的解決方案。

爲您的代碼進行測試是恕我直言,代碼味道。

另請注意,as: Submodule是默認值,因此不需要。

1

大廈從lab419和dylanthepiguy答案:

模塊與文檔測試:

defmodule SomeLongModuleName.SubModule do 
    @doc """ 
     iex> SubModule.add(x, y) 
     3 
    """ 
    def add(x, y) do 
    x + y 
    end 
end 

測試用例模塊,文檔測試:

defmodule SomeLongModuleName.SubModuleTest do 
    use ExUnit.Case, async: true 

    # Alias the submodule so we don't have to use the fully qualified name 
    alias SomeLongModuleName.SubModule 

    doctest SomeLongModuleName.SubModule, import: true 
end