1

I'm trying to set a result on a constructor call in an Expectations block, but the constructor call in the tested code doesn't return the result I'm setting. There must be a different way to do this, the code below is my attempt, and fails on the assertEquals. Does anyone know how to do this?

Note that I want to isolate my unit test from production code, I am testing SomeMapper so I want to mock OutputObject (in my real-world code, OutputObject is a complex object that might have unexpected behavior when used in a test)

public class SomeMapperTest
{
   // "production code"
   public class InputObject
   {
      private long one, two;
      private String name;

      public long getOne()
      {
         return one;
      }

      public long getTwo()
      {
         return two;
      }

      public String getName()
      {
         return name;
      }
   }


   public class OutputObject
   {
      public OutputObject(String name, MyObject myObject1, MyObject myObject2)
      {
      }
   }


   public class MyObject
   {
      public MyObject(long l)
      {
      }
   }


   public class SomeMapper
   {
      public OutputObject map(InputObject input)
      {
         return new OutputObject(input.getName(), new MyObject(input.getOne()), new MyObject(input.getTwo()));
      }
   }
   // end "production code"

   // test code begins here...

   //@Tested
   private SomeMapper someMapper = new SomeMapper();


   @Test
   public void testMap(@Mocked InputObject input, @Mocked MyObject myObject1, @Mocked MyObject myObject2, @Mocked OutputObject expectedResult)
   {
      final String NAME = "name";
      final long ONE = 1L;
      final long TWO = 2L;

      new Expectations()
      {{
         input.getName();
         result = NAME;
         input.getOne();
         result = ONE;
         input.getTwo();
         result = TWO;

         new MyObject(ONE);
         result = myObject1;

         new MyObject(TWO);
         result = myObject2;

         new OutputObject(NAME, myObject1, myObject2);
         result = expectedResult;
      }};

      OutputObject result = someMapper.map(input);
      assertEquals("Not same!", expectedResult, result);
   }
}
Lin Du
  • 88,126
  • 95
  • 281
  • 483
eriksmith200
  • 2,159
  • 5
  • 22
  • 33
  • There is nothing to be mocked in this test. Simply instantiate an `InputObject` in the test, pass it in the call to `map`, and then verify the returned `OutputObject`. – Rogério Oct 10 '19 at 20:06
  • @Rogério you mean just assert the values of OutputObject properties? The code I posted is an example to show the problem, in my "real" code, OutputObject is a complex class that takes a lot of code to instantiate, so that is why I would like to mock it and verify the constructor call. I will probably also need to write a Verifications block in which I would like to verify that certain setter methods are called. – eriksmith200 Oct 11 '19 at 08:12

0 Answers0