New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Mocking case classes and classes without default constructor #56
Comments
Currently ScalaMock can only mock classes with a default constructor. If your case class has a default constructor, you should be able to mock it just like a regular class. Example: src/main/scala/Foo.scala case class Foo(a: Int, b: String) {
def this() = this(1, "asdf") // default constructor
def something(): Int = 3
} src/test/scala/FooTest.scala import org.scalatest._
import org.scalamock.scalatest.MockFactory
class FooTest extends FlatSpec with Matchers with MockFactory {
"Case class" should "be mocked" in {
val foo = mock[Foo]
(foo.something _).expects().returning(5)
foo.something() should be(5)
}
} |
You don't have to modify your production code by adding a default constructor to case classes. Example. For case class: case class CaseClass(integer : Int, string : String) {
def method() : Integer = integer + 100
} You can workaround this ScalaMock issue by extending given case class in test code and providing some fake/mock arguments, e.g: class MockableCaseClass extends CaseClass(0, null)
val m = mock[MockableCaseClass]
(m.method _).expects().returning(5) We can easily extend |
This strategy works but requires quite a bit of boilerplate in a project that has a lot of case classes. Being able to |
👍 |
👍 This would be great if we could avoid the boiler plate. |
👍 |
👍 |
11 similar comments
👍 |
+1 |
👍 |
👍 |
👍 |
👍 |
👍 |
👍 |
👍 |
+1 |
👍 |
👍 |
1 similar comment
👍 |
I have made PR. Please make review. |
+1 |
1 similar comment
+1 |
+1 |
+1 |
6 similar comments
+1 |
+1 |
+1 |
+1 |
+1 |
+1 |
paulbutcher#56 Mocking class with nonempty default constructor
just merged some code into master to support constructors with parameters, see PR #163 |
👍 |
I still (in 3.6.0) seem to experience an NPE on mocking a class class TableLactationCurves(stream: InputStream) extends DataSetXml(stream) with LactationCurves { The problem is in the class DataSetXml(stream: InputStream) {
protected var dataTypes: mutable.Map[String, DataType] = mutable.Map()
protected var data: Array[Array[Any]] = null
private var description: String = null
try {
val is = new InputSource()
is.setCharacterStream(new StringReader(Utils.readStringFromInputStream(stream)))
loadData(null, is)
} catch {
case ex: Exception =>
throw new RuntimeException(ex)
} Of course, i could fix this by not throwing a Update: As a workaround, I changed this horrid Java-esque (largely translated by IntelliJ) code to have constructors that have |
Your constructor works on the |
How would I mock case classes?
The text was updated successfully, but these errors were encountered: