0

I have a service:

@Service
class ArchiveService(
        val fnaReactiveClient: FNAReactiveClient,
        val resolvedTopicPrefix: String)

And I have Config:

@Configuration
@EnableAspectJAutoProxy(proxyTargetClass = true)
class CoreKafkaConfig {
    
    @Value("\${kafka.topicPrefix:}")
    lateinit var topicPrefix: String

    @Bean
    fun resolvedTopicPrefix() = run {
        KafkaTopicsUtil.resolveTopicPrefix(topicPrefix)
    }

But in my test:

@ExtendWith(MockitoExtension::class)
class ArchiveServiceTest {

    @InjectMocks
    lateinit var archiveService: ArchiveService

    @Mock
    lateinit var fnaReactiveClient: FNAReactiveClient

    
 @Test
    fun `create archive with duplicate filenames`() {
        val user = "user"
      
... some when and given block ....

        val newDocVer = archiveService.archiveDoc("integration", null, req, ecmHeaders, EcmServiceAsyncConfig.MethodType.ARCHIVE)
       assertEquals(newId, newDocVer)
       
... some verify block ....
        }
    }

I have an exception:

Cannot instantiate @InjectMocks field named 'archiveService' of type 'class tu.xxxx.ecm.services.service.ArchiveService'. You haven't provided the instance at field declaration so I tried to construct the instance. However the constructor or the initialization block threw an exception : Parameter specified as non-null is null: method tu.xxx.ecm.services.service.ArchiveService., parameter resolvedTopicPrefix

What i am doing wrong????

1 Answers1

0

The problem is that you require two arguments to create ArchiveService. But... only one mock is defined. Remember, that while performing unit test, beans are not created and Spring DI injection is not performed.

So, what you can do. In fact - not a lot. Please see this thread: Injecting a String property with @InjectMocks

There are some workarounds, however, the one could argue about readability of such an approach.

So, what I suggest is not using @InjectMock in your test:

@ExtendWith(MockitoExtension::class)
class ArchiveServiceImplTest {

    lateinit var instance: ArchiveServiceImpl

    @Mock
    lateinit var clientMock: Client

    @BeforeEach
    fun setup() {
        instance = ArchiveServiceImpl(clientMock, "fakeId")
    }

    @Test
    fun test() {
        instance.archive("")
    }
}
Cililing
  • 4,303
  • 1
  • 17
  • 35