Jmockit mocked constructor does not return expected value

I'm trying to unit test a class in which one of its methods returns an instance of a co-author's class: depending on the values โ€‹โ€‹of its arguments, it either returns a newly created instance or a saved previously created instance.

I make fun of the constructor call in Expectations and set the result to a value that is a mocked copy of the collaborator. But when I test a method with parameters that force it to create a new instance, the constructed constructor and, therefore, the method does not return the expected value.

I simplified this to the following:

package com.mfluent; import junit.framework.TestCase; import mockit.Expectations; import mockit.Mocked; import mockit.Tested; import org.junit.Assert; import org.junit.Test; public class ConstructorTest extends TestCase { static class Collaborator { } static class ClassUnderTest { Collaborator getCollaborator() { return new Collaborator(); } } @Tested ClassUnderTest classUnderTest; @Mocked Collaborator collaborator; @Test public void test() { new Expectations() { { new Collaborator(); result = ConstructorTest.this.collaborator; } }; Collaborator collaborator = this.classUnderTest.getCollaborator(); Assert.assertTrue("incorrect collaborator returned", collaborator == this.collaborator); } } 

Any ideas on why this test fails and how to get it to work will be greatly appreciated.

Thanks in advance,

Jim Renkel Senior Technical Staff mFluent, Inc. LLC

+4
source share
1 answer

Change the @Mocked annotation to @Capturing , for example:

 @Capturing Collaborator collaborator; 

This allows me to take the test for me.

In my opinion, this is a bit of voodoo magic, but if you want to read more, see Capturing internal instances of mockinged types in the JMockit tutorial.

Also see Using JMockit to return the actual instance from the mocked constructor

+1
source

Source: https://habr.com/ru/post/1481051/


All Articles