type or paste code here
object MyObject {
// Method that takes a String (name) as parameter and returns a greeting message
def greet(name: String): String = {
s"Hello, $name! Welcome to Scala!"
}
// Main method to test the greet method
def main(args: Array[String]): Unit = {
val message = greet("Alice") // Calling the greet method
//Line1
//Line2
println(message) // Output: Hello, Alice! Welcome to Scala!
}
}
consider the above code sample ,
if i want to mock this
MyObject
and change the behaviour of greet method
How can i achieve this .
Even in main method also
I have 2 lines i want to mock the behaviour of those two lines , how can i achieve that , can someone pls suggest
You probably can get what you want using something like mockito.
I can’t help you with the code, though, since I have never, nor plan ever, to use that kind of library or do this kind of thing.
Rather, I would refactor the code to allow proper testing without needing runtime magic.
I tried using the mockito and use the methods like mockstatic but that is not working , after going through the documentation i found that’s not possible .
I’ll echo @BalmungSan’s suggestion of refactoring – over the years, I’ve moved away from ever using mocks, which tend to result in terrible tests.
Instead, it’s all about the traditional guideline for good design: always separate interface from implementation.
In particular, be sparing with objects. Only put a method in an object if you are absolutely certain that you will never want a test-substitute for it. Otherwise, it’s best to define an interface that can be easily replaced in tests, and a class that implements that interface.
This, in turn, means that the singleton pattern is pretty dangerous for applications of non-trivial size. I don’t use it much, personally, for exactly this reason – I use dependency injection of one sort or another the vast majority of the time.
(Note that little of this is really all that Scala-specific. These are techniques I started evolving back in my C++ days, 25 years ago, and was refining via C# before I got to Scala.)
A good general advice would be to think about the testability of your application upfront. That would mean not putting things that you may have to mock in singleton objects, but putting those things behind an interface. E.g.
trait Greeter {
def greet(name: String): String
}
class Application(greeter: Greeter) {
def run(): Unit = {
val message = greeter.greet("Alice")
...
println(message)
}
}
object Main {
def main(args: Array[String]): Unit = {
val greeter = new GreeterImpl()
val application = new Application(greeter)
application.run()
}
}
Then you can still use whatever you want for testing. Either mockito, handwritten mocks, …