简体   繁体   中英

How to mock methods using mockito?

I have an abstract class and a derived class. The derived class is a serivce so is autowired into the test class. Theres a method in the abstract class that I need to mock and test. My current implementation is not working and I'm not sure why.

I've created a spy of the class I want to test and I've called the method using the spy in the test. But still mockito fails to return my mocked value.

abstract class AbstractMyClass {
    fun hello(): String {
        "bello"
    }
}

@Service
class MyClass: AbstractMyClass() {}

My Test stub is

@Autowired
private lateinit var myClass: MyClass


@Test
fun `test hello`() {
  val spy = Mockito.spy(myClass)
  Mockito.doReturn("cello").`when`(spy).hello()
  val res = spy.hello()
  Assert.assertEquals("cello", res)
}

What am I doing wrong here?

In Kotlin, the methods are final by default. Thus, AbstractMyClass::hello() is final and since you never override it in MyClass it remains so and Mockito will not stub it.

To get the above code to work you need to open the method in AbstractMyClass :

abstract class AbstractMyClass {
    open fun hello(): String {
        "bello"
    }
}

BTW, it is unclear from your example what exactly you are trying to test. I don't suppose you are testing the behaviour of MyClass here...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM