qiGuar
qiGuar

Reputation: 1804

Mockito set field when call getter

I'm testing method and have a problem that my entity has a field that is null, but i need it not to be empty. I have this:

class MyClass {

    void myMethod() {
        Entity entity = new Entity();
        String str = entity.getField(); // It's null now
        if (str == null) { //always true
            //do something
        }
    }
}

Now in test i need my field not to be null.
I tried to do the following in test:

Entity entity = mock(Entity.class);
when(entity.getField()).thenReturn("text");

But it seems, that it doesn't work. The problem is that I can't use PowerMock or refactor original class.
Is there any way I can return text or set field before if statement?

Upvotes: 0

Views: 1750

Answers (3)

chenrui
chenrui

Reputation: 9876

I have similar problem before, what I have done is to create a separate wrapper method to inject the dependency for unit testing.

For example, in here, you can create wrapperMyMethod() to solve the issue, the code would be:

void wrapperMyMethod(){
    Entity entity = new Entity();
    void myMethod(entity);
}
void myMethod(Entity entity) {
    String str = entity.getField(); 
}

Hope this solves your issue.

Upvotes: 0

Duncan Jones
Duncan Jones

Reputation: 69399

Looking at your code, you have no way of injecting a mocked Entity instance into your method.

You must adjust your MyClass so that it accepts an Entity object, thus allowing you to pass a mocked object for the purposes of testing. Without this, you cannot expect to be able to mock objects.

class MyClass {

    private Entity entity;

    public MyClass(Entity entity) {
      this.entity = entity;
    }

    void myMethod() {
        String str = entity.getField(); // It's null now
        if (str == null) { //always true
            //do something
        }
    }
}

If you don't want to change the public facing constructor, consider adding a package-private setter method that lets you tweak the Entity instance. But you must store the instance as a field to allow you to change it from your test code.

Upvotes: 3

pasha701
pasha701

Reputation: 7207

Possible, "spy()" can be used instead of "when()": http://docs.mockito.googlecode.com/hg/org/mockito/Mockito.html#13

Upvotes: 0

Related Questions