Matlab: Improper index matrix reference (or outsmarting matlab)

前端 未结 5 2257
梦谈多话
梦谈多话 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:06

    Here's an examplary implementation with an overloaded subsref method. It could also be done with only one class I guess, but that would make the subsref-overloading even uglier.

    classdef Tester < handle
        methods
            function obj = Tester()
            end
    
            function [varargout] = subsref(this,S)
    
                if S(1).type(1) =='('
                    tv = TestValue(S(1).subs{:});
                end
    
                if numel(S) > 1
                    try
                        [varargout{1:nargout}] = builtin('subsref', tv, S(2:end));
                    catch me
                        me.throwAsCaller();
                    end
                else
                    varargout{1} = tv;
                end
    
            end
        end
    end
    

    And

    classdef TestValue 
        properties (Hidden)
            value;
        end
        methods
            function this = TestValue(value)
                this.value = value;
            end
    
            function toBe(this, v)
                assert( isequal(this.value, v) );
            end
        end
    end
    

    Results in:

    >> expect(1).toBe(1)
    >> expect(1).toBe(2)
    Error using TestValue/toBe (line 13)
    Assertion failed.
    

提交回复
热议问题