Mocking interfaces - Manual - AxUnit - AxUnit - AxUnit,

AxUnit (legacy) CLI Tool (test)

Portfolio
SIMATIC AX
Product
AxUnit
Software version
2.0.9
Edition
08/2025
Language
English (original)
Package Name
@ax/axunit-docs

An interface implementation could be mocked when the interface is declared as a variable in the test fixture. In the below example, the interface IFoo is implemented by the class ConcreteFoo. The implemented method Return_2 is mocked in the test by using the i: IFoo declaration. Specially note that here if the user uses the concrete implementation of IFoo, that is c: ConcreteFoo then the mock would give wrong results.

NAMESPACE Library
    INTERFACE IFoo
        METHOD Return_2 : INT END_METHOD
    END_INTERFACE

    CLASS ConcreteFoo IMPLEMENTS IFoo    
        METHOD PUBLIC Return_2 : INT
            Return_2 := 2;
        END_METHOD
    END_CLASS

    CLASS UseInterface
        VAR PRIVATE
            i : IFoo;
        END_VAR

        METHOD PUBLIC Act
            VAR_OUTPUT
                result : INT;
            END_VAR
            result := i.Return_2();
        END_METHOD

        METHOD PUBLIC Init
            VAR_INPUT
                a : IFoo;
            END_VAR
            i := a;
        END_METHOD
    END_CLASS

END_NAMESPACE
The interface IFoo implementation is then mocked by
USING Library;
USING AxUnit;

NAMESPACE MyTest

    {TestFixture}
    CLASS MyTestFixture
        VAR
            i : IFoo;  //not i: ConcreteFoo
            user : UseInterface;
        END_VAR

        {Test}
        METHOD PUBLIC TestInterfaceUsage
            VAR
                res : INT;
            END_VAR

            AxUnit.Mocking.Mock(NAME_OF(i.Return_2), NAME_OF(Return_1));
            user.Init(i);

            user.Act(result => res);
            Assert.Equal(res, 1);            
        END_METHOD

        METHOD Return_1 : Int
            Return_1 := 1;
        END_METHOD

    END_CLASS

END_NAMESPACE