How to mock IContext object in JUnit tests

4
Hello! I am trying to write JUnit tests but I am coming across an issue that lot of classes seem to have IContext as member variable. Is there a way of mocking IContext? The close coupling between business objects and IContext may be an issue itself since IContext is hardly used apart from when the methods on Mendix generated proxies are called. Mocking IContext in Junit tests will be much easier and a preferred option to refactoring of the existing code. Thanking in advance Ivan
asked
1 answers
6

It depends on what you're trying to do exactly, but IContext is simply an interface. It shouldn't be too hard to build your own mock object which implements the IContext.

ie:

package com.mendix;

import java.util.List;
import java.util.UUID;

import com.mendix.systemwideinterfaces.core.IContext;
import com.mendix.systemwideinterfaces.core.ICoreAction;
import com.mendix.systemwideinterfaces.core.IMendixIdentifier;
import com.mendix.systemwideinterfaces.core.ISession;

public class MockContext implements IContext {

    @Override
    public void addVariable(String name, Object value) {}

    @Override
    public void endTransaction() {}

    @Override
    public List<? extends ICoreAction<?>> getActionList() {
        return null;
    }

    @Override
    public List<IMendixIdentifier> getContextObjects() {
        return null;
    }

    @Override
    public long getCurrentGUID() {
        return 0;
    }

    @Override
    public IMendixIdentifier getCurrentIdentifier() {
        return null;
    }

    @Override
    public String getCurrentObjectType() {
        return null;
    }

    @Override
    public ISession getSession() {
        return null;
    }

    @Override
    public UUID getTransactionId() {
        return null;
    }

    @Override
    public Object getVariable(String variableName) {
        return null;
    }

    @Override
    public boolean hasPermission(String actionName) {
        return false;
    }

    @Override
    public boolean isInTransaction() {
        return false;
    }

    @Override
    public void rollbackTransAction() {}

    @Override
    public void setContextObjects(List<IMendixIdentifier> contextObjects) {}

    @Override
    public void setCurrentIdentifier(IMendixIdentifier currentIdentifier) {}

    @Override
    public void setCurrentObjectType(String currentObjectType) {}

    @Override
    public void startTransaction() {}

    @Override 
    public MockContext clone() {
        return null;
    }

}
answered