Kotlin测试的UnfinishedStubbingException

时间:2018-12-16 04:50:02

标签: spring kotlin mockito

我正在将一些Java代码转换为Kotlin,并且我得到了以下代码的UnfinishedStubbingException异常:

@RunWith(SpringRunner::class)
@SpringBootTest(classes = [FormsApplication::class])
class AccountResourceIntTest {

    @Autowired
    lateinit var userRepository: UserRepository

    @Autowired
    lateinit var authorityRepository: AuthorityRepository

    @Autowired
    lateinit var userService: UserService

    @Autowired
    lateinit var passwordEncoder: PasswordEncoder

    @Autowired
    lateinit var httpMessageConverters: Array<HttpMessageConverter<*>>

    @Autowired
    lateinit var exceptionTranslator: ExceptionTranslator

    @Mock
    lateinit var mockUserService: UserService

    @Mock
    lateinit var mockMailService: MailService

    private lateinit var restMvc: MockMvc

    private lateinit var restUserMockMvc: MockMvc


    @Before
    fun setup() {
        MockitoAnnotations.initMocks(this)
        doNothing().`when`(mockMailService).sendActivationEmail(any()) <-- exception
        ...
    }
    ...
}

堆栈跟踪:

org.mockito.exceptions.misusing.UnfinishedStubbingException: 
Unfinished stubbing detected here:
-> at com.application.web.rest.AccountResourceIntTest.setup(AccountResourceIntTest.kt:82)

E.g. thenReturn() may be missing.
Examples of correct stubbing:
    when(mock.isOk()).thenReturn(true);
    when(mock.isOk()).thenThrow(exception);
    doThrow(exception).when(mock).someVoidMethod();
Hints:
 1. missing thenReturn()
 2. you are trying to stub a final method, which is not supported
 3: you are stubbing the behaviour of another mock inside before 'thenReturn' instruction if completed

    at com.application.service.UserServiceIntTest.init(UserServiceIntTest.kt:64)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    ...

MailService class被标记为open

@Service
open class MailService {
    ...
    @Async
    fun sendActivationEmail(user: User) {
        log.debug("Sending activation email to '{}'", user.email)
        sendEmailFromTemplate(user, "mail/activationEmail", "email.activation.title")
    }
}

我正在从以下方式转换此测试的Java代码:

@Before
public void setup() {
    MockitoAnnotations.initMocks(this);
    doNothing().when(mockMailService).sendActivationEmail(any());
    ...
}

错误指向丢失的thenReturn语句,但这在原始Java代码中不是必需的。这是怎么回事?

1 个答案:

答案 0 :(得分:1)

通过将以下代码添加到SELECT ID, REVERSE(PARSENAME(REVERSE(WebsiteName), 2)) FROM dbo.YourTable .....类中解决了该问题

AccountResourceIntTest

发现该问题及其解决方法的说明here