如何访问fortran模块中的私有变量?

Nor*_*ico 1 fortran

我知道私有变量的想法是不应该访问它们,并且我确实希望它在程序的其余部分中使用模块时以这种方式工作,但我需要它来检查内部工作的模块.

说我有以下简化示例:

module mod
  implicit none
  private
  integer :: value
  public :: set_value

contains

subroutine set_value(input)
  implicit none
  integer,intent(in) :: input
  value=input
end subroutine

end module
Run Code Online (Sandbox Code Playgroud)

我现在想测试子程序,看看它是否实际上正在做我想要的:我想编写一个使用该模块的程序,set_value用输入8 调用例程,然后检查内部变量value现在是否为8.

我可以这样做吗?或者它是否有另一种单元测试私有变量初始化器的方法?

cas*_*sey 6

You have three approaches as I see them.

  1. write a get function to get the value and test. You indicate in the comments that this is sub-optimal though, so..

  2. If you have a compiler with Fortran 2003 support (e.g. any recent version of a modern Fortran compiler), declare the variable with the protected attribute instead of the private attribute. This will allow your variable to be read from any code, but not modified. This will enforce that it can only be set via your setter function but you can inspect its value directly in your unit test.

    integer, protected :: value
    
    Run Code Online (Sandbox Code Playgroud)
  3. Lastly, if all else fails, you can conditionally compile the module so that sometimes the variable is not private. For example, do this:

    module mod
      implicit none
      private
      integer :: value
      public :: set_value
    
    #ifdef UNITTESTING
      public :: value
    #endif
    
    contains
    ...
    end module
    
    Run Code Online (Sandbox Code Playgroud)

    然后将文件名从更改为.f90,.F90以便对其进行预处理(至少在gfortran和ifort上).当你正常编译时,value它将是私有的,但如果你用标志编译,-DUNITTESTING那么value将是公共的.编译测试用例时,使用该标志,现在可以直接检查变量.