2

I´m trying to write some unit tests for my company, so its not possible for me to change anything in sourceCode but everything in the tests. I´m using Java8, Spring, Mockito and JUnit4.

Problem: There are some services with a entityManager, which gets instantiated via dependencyInjection

@PersistenceContext(unitName = someName)
private EntityManager em;

I tried to mock this and injecting it into my ClassUnderTest, like i mocked every other class but that doesn´t work.

@InjectMocks
@Autowired
private SomeService testedSomeService;

There´s always an "IllegalStateException: Failed to load application context" before running the first test, with a hint to the entity manager. If i make the annotation to a comment, every method gets tested fine (except the methods, using entityManager).

Is there a simple way to mock the entityManager? or how can i inject a dependency in my testclass?

I appreciate ANY help!

tod3rt
  • 21
  • 1
  • 3

2 Answers2

0

Try this:

@RunWith(MockitoJUnitRunner.class)
public class Test {

    @Mock
    private EntityManager em;

    @Before
    public void setUp(){
        MockitoAnnotations.initMocks(this);
        Mockito.reset(em);
    }

    //your junits

}
SirCipher
  • 933
  • 1
  • 7
  • 16
Tarun Jain
  • 262
  • 1
  • 8
0

Of course you can. You use @Mock, that's all. @InjectMocks is for the service which uses EntityManager, not for EntityManager. And @Autowired is for real instanciation and injection via context, which only exists in an integrated test, not in an unit test, as what you do here. Just use @Mock.

WesternGun
  • 11,303
  • 6
  • 88
  • 157