0

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?

2
  • Is your problem that you cannot inject your Entity instance? Commented Nov 13, 2013 at 11:00
  • I go into if statement, which means, that str is still null. Commented Nov 13, 2013 at 11:01

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.