ETartaren
ETartaren

Reputation: 170

How to mock EntityManager in ConstraintValidator implementation

I already have mock EntityManager in the test. But now I need mock EntityManager also in my real class(validator of the custom constraint annotation).

In the test I doing so

@RunWith(MockitoJUnitRunner.class)
public class SomeConstraintValidatorTest {

    @Mock
    private EntityManager entityManager;

In the validator I can not do the same, because can not resolve import org.junit.runner.RunWith in Intellij Idea. For build I'm using Gradle.'gradle deploy' going successfully, but when I start Test I get following errors in Idea console

Error:(6, 25) java: package org.junit.runners does not exist Error:(21, 2) java: cannot find symbol symbol: class RunWith

The reasons on which I need mock EntityManager is error below while testing

org.hibernate.AssertionFailure: null id in com.clients.entity.CClient entry (don't flush the Session after an exception occurs)

Upvotes: 0

Views: 783

Answers (2)

ETartaren
ETartaren

Reputation: 170

I don't know why the field injection does not works, but I have found another solution of the original problem. Before the line where I got an exception i'm wrote

entityManager.setFlushMode(FlushModeType.COMMIT);

Upvotes: 0

Vjeetje
Vjeetje

Reputation: 5384

The @RunWith annotation is made for test classes only. If you want to inject the EntityManager in your validation class, I would recommend using field injection.

I assume your ConstraintValidator has a field with the name 'entityManager'.

@RunWith(MockitoJUnitRunner.class)
public class SomeConstraintValidatorTest  {
    @Mock
    private EntityManager entityManager;
    @InjectMocks
    private ConstraintValidator myValidator;
}

more information can be found here

Upvotes: 1

Related Questions