Reputation: 1337
I have the following code, and I was wondering how to mock the component used in the value annotation. It is not instantiated in the model class, so I can't really use the annotation @InjectMocks
, how do I perform a mock in this context?
public interface Vehicule {
@Value('#{target.VEHICULE_ID}')
BigInteger getId();
@Value('#{@mapperUtility.clobToString(target.CERTIFICATE)}') // How to mock this call?
String getCertificate();
}
@Component
public class MapperUtility {
public String clobToString(Clob clob) {
return (clob == null) ? null : ClobType.INSTANCE.toString(clob); // from org.hibernate.type
}
}
public interface VehiculeRepository extends JpaRepository<Vehicule, String> {
@Query(value = SQL_QUERY_FIND_VEHICULE_BY_IDS)
List<Vehicule> findVehiculeByIds(@Param("Ids") List<BigInteger> ids);
}
What would a test that mocks the component inside the value annotation would look like?
Upvotes: 1
Views: 209
Reputation: 8886
This is a pretty common issue when using direct field injection. We solved this problem by writing a Junit5 extension: http://github.com/exabrial/mockito-object-injection
This allows you to cleanly inject data into private members of a class under test, without resorting to fire up an entire container for an integration test.
Example:
@TestInstance(Lifecycle.PER_CLASS)
@ExtendWith({ MockitoExtension.class, InjectExtension.class })
class MyControllerTest {
@InjectMocks
private MyController myController;
@Mock
private Logger log;
@Mock
private Authenticator auther;
@InjectionSource
private Boolean securityEnabled;
@Test
void testDoSomething_secEnabled() throws Exception {
securityEnabled = Boolean.TRUE;
myController.doSomething();
// wahoo no NPE! Test the "if then" half of the branch
}
Upvotes: 1