4

Using JUnit for testing classes-

Have a class TestAccess.java having

static private TestAccess instance = new TestAccess();
public static TestAccess getTestAccess() {
    returns instance;
}

For testing a test class A.java used JMockit to mock the getTestAccess method

@Mock
TestAccess mockTestaccess;    

@Test
public void testMethod() {
    new MockUp<TestAccess>() {
        @mockit.Mock
        public TestAccess getTestAccess() {
            return mockTestaccess;
        }
    };

    TestAccess test=TestAccess.getTestAccess();
}

In another class B.java I don't want to use mock and call TestAccess.java as follows

@Test
public void doTest()
{ 
    TestAccess test=TestAccess.getTestAccess();
}

B.java if run independently, the real TestAccess instance is returned and works fine.

However during maven run it fails as even in B.java the TestAccess.getTestAccess() return the mock defined in A.java and not the real instance as expected.

Could anyone guide how can this be resolved.

Vampire
  • 35,631
  • 4
  • 76
  • 102

1 Answers1

1

afair your example will not even run, as the @Mock annotation on the mockTestaccess field is not valid. I guess it should be @Mocked? And if so, there is no need to additionally use the new MockUp(), as @Mocked on mockTestaccess will already mock away all instances of TestAccess during the tests of that test class and afterwards will be reverted automatically. If you problem is, that getTestAccess() returns some subclass of TestAccess which then is not a mocked instance you might want to have a look at @Capturing which also mocks instances of subclasses.

Vampire
  • 35,631
  • 4
  • 76
  • 102
  • I am using Junit for unit testing. Use @mock(org.mockito.Mock) to mock the instance. Since i wanted to mock a static method so used jMockito(mockit.MockUp). Have just edited the above statement to include mockit.MockUp which i had missed. Also the test cases do run. –  Sep 01 '16 at 10:27
  • 1
    You are mixing two different mocking frameworks? Why that? I'd recommend to not mixing mocking frameworks but to only use JMockit. – Vampire Sep 01 '16 at 10:41