Matlab: Improper index matrix reference (or outsmarting matlab)

前端 未结 5 2253
梦谈多话
梦谈多话 2021-02-09 16:47

I want to be able to write jasmine-like tests in Matlab. So something like

expect(myfibonacci(0)).toBe(0);
expect(myfibonacci(5)).toBe(15);
expect(myfibonacci(10         


        
5条回答
  •  一生所求
    2021-02-09 17:09

    To add to @MohsenNosratinia's remark, if you use nested-functions/closure instead of OOP classes, you get the yet another inconsistency:

    function obj = expect(expr)
        obj = struct();
        obj.toBe = @toBe;
        function toBe(expected)
            assert(isequal(expr,expected))
        end
    end
    
    1. The syntax doesn't work from the command prompt:

      >> expect(1+1).toBe(2)
      Undefined variable "expect" or class "expect". 
      
    2. Doesn't work either from a script:

      testScript.m

      expect(1+1).toBe(2)
      expect(1*1).toBe(2)
      

      with the same error as before:

      >> testScript
      Undefined variable "expect" or class "expect".
      Error in testScript (line 1)
      expect(1+1).toBe(2)
      
    3. But for an M-file function:

      testFcn.m

      function testFcn
          expect(1+1).toBe(2)
          expect(1*1).toBe(2)
      end
      

      it is strangely accepted:

      >> testFcn
      Error using expect/toBe (line 5)
      Assertion failed.
      Error in testFcn (line 3)
          expect(1*1).toBe(2) 
      

      (the second assertion failed as expected, but no syntax errors!)


    I consider throwing a "syntax error" to be the correct outcome here, as you should not directly index into the result of a function call. If you do, I think of it as "undefined behavior" :) (it might work, but not in all cases!)

    Instead, you should first store the result in a temporary variable, then apply indexing into it:

    >> obj = expect(1+1);
    >> obj.toBe(2);
    

    or resort to ugly hacks like:

    >> feval(subsref(expect(1+1), substruct('.','toBe')), 2)
    

    or even undocumented functions:

    >> builtin('_paren', builtin('_dot', expect(1+1), 'toBe'), 2)
    

提交回复
热议问题