How to run scala tests with junit 4? - unit-testing

I can't run following code with IDEA
#Test
class CompanyURLTest extends Assert {
#Test
def test = assert(false);
}
It runs, but J-Unit says that there are not test to run

I generally use ScalaTest in combination with the Junit4 runner so that Maven sees and executes my tests. I like the Spec/FlatSpec/WordSpec semantics for organizing tests. I'm experimenting with the ShouldMatchers but I have used JUnit for so long that asserts just seem a bit more natural to me.
Here's an example:
import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner
import org.scalatest.FlatSpec
import org.scalatest.matchers.ShouldMatchers
#RunWith(classOf[JUnitRunner])
class BlogFeedHandlerTest extends FlatSpec with ShouldMatchers with Logging {
"the thingy" should "do what I expect it to do" in {
val someValue = false;
assert(someValue === false)
}
}
The ScalaTest docs are at http://www.scalatest.org/

The following works for me
import org.junit._
import Assert._
class MyTest {
#Test
def test = assert(false)
}

The #org.junit.Test annotation is only applicable for methods: #Target({ElementType.METHOD}).
Also keep in mind that test methods must return Unit.
import org.junit.Assert._
import org.junit.Test
class CompanyURLTest {
#Test def test = assertFalse(false)
}

Even though it's late - Gradle site surprisingly has a lot of good tutorials showing how to support Scala tests.
https://guides.gradle.org/building-scala-libraries/#review_the_generated_project_files

Related

Grails Unit Test does not work when dependency inject is necessary

I am trying to run my unit tests in Grails 4.0.3 through the command grails test-app.
Unfortunately I am in trouble with dependency injection.
I have basically two test cases. The first one does not work with the response No GORM implementations configured. Ensure GORM has been initialized correctly It seems that PidService is not correctly injected.
To demonstrate my suspicion I created a private method which only throws an exception, to be invoked in the second test case. So, I invoked that method in the second one and it worked as expected. The exception was correctly catched and I could verify that the message is correct.
package br.gov.cmb.pid.tests
import br.gov.cmb.pid.services.PidService
import grails.testing.services.ServiceUnitTest
import org.grails.web.json.JSONObject
import spock.lang.Specification
class PidIssuingSpec extends Specification implements ServiceUnitTest<PidService> {
def setup() {
}
def cleanup() {
}
def "Test that injection is not working"() {
given:
JSONObject wrongPidIssuingDocument = new JSONObject()
when:
service.buildPidIssuingOrder(wrongPidIssuingDocument)
then:
def e = thrown(Exception)
e.message == "Register number is mandatory."
}
def "Test that works because no injection is necessary"(){
when:
dispException()
then:
def e = thrown(Exception)
e.message == "Register number is mandatory."
println(e.message)
}
private void dispException(){
throw new Exception("Register number is mandatory.")
}
}
Grails Unit Test does not work when dependency inject is necessary
In general unit tests that require dependency injection is supported.
See the Modifying the Application Context section at https://testing.grails.org/2.4.1/guide/index.html#unitTesting. That demonstrates how to add beans to the context in a unit test so they may be injected. For example, you could do this:
Closure doWithSpring() {{ ->
// create a bean named "someService" which
// is an instance of SomeService.
// the someService bean may be injected into the
// the class under test
someService(SomeService)
}}
At https://github.com/grails/grails-testing-support/blob/9f782ff3b911919e421440feb8a2e4736c6aced6/examples/demo33/src/test/groovy/demo/ReportingServiceSpec.groovy is a working example:
package demo
import grails.testing.services.ServiceUnitTest
import spock.lang.Specification
class ReportingServiceSpec extends Specification implements ServiceUnitTest<ReportingService> {
Closure doWithSpring() {{ ->
someHelper RushHelper
}}
void "test dependency injection"() {
expect:
service.retrieveSomeNumber() == 2112
}
}
class RushHelper implements MathHelper {
#Override
int getSomeNumber() {
2112
}
}
Notice that the service being tested is the ReportingService. The RushHelper is being injected into that service to support the test.

MediatorLiveData doesn't work in JUnit tests?

So I've tried using MediatorLiveData for the rather simple use-case of converting an ISO country code (e.g. "US") to a country calling code (e.g. "+1") through the use of libphonenumber. The resulting screen works fine, but seems to fail JUnit tests, even when InstantTaskExecutorRule is used.
Example minimal unit test (in Kotlin) that I believe should pass, but fails instead:
import android.arch.core.executor.testing.InstantTaskExecutorRule
import android.arch.lifecycle.MediatorLiveData
import android.arch.lifecycle.MutableLiveData
import org.junit.Assert.assertEquals
import org.junit.Rule
import org.junit.Test
class MediatorLiveData_metaTest {
#get:Rule
val instantTaskExecutorRule = InstantTaskExecutorRule()
#Test
fun mediatorLiveData_metaTest() {
val sourceInt = MutableLiveData<Int>()
val mediatedStr = MediatorLiveData<String>()
mediatedStr.addSource(sourceInt) {
mediatedStr.value = it.toString()
}
sourceInt.value = 123
assertEquals("123", mediatedStr.value) // says mediatedStr.value is null
}
}
Thanks to Reddit user matejdro; the answer was that like Schrödinger's proverbial cat, MediatorLiveData won't update itself unless observed, so I'd need a mediatedStr.observeForever{} to force it to update itself.

Grails integration test - redirect action returns null

This is a small integration Junit that I'm having difficulty with. I've re-written this several different ways and the current way is straight out of the Grails manual - but it still returns null. I don't see the error; I thought it might be a spelling error but I've checked all those. I've tried redirectUrl and redirectedUrl - still returns null.
Controller snippet:
#Transactional(readOnly = true)
def saveReportError() {
redirect(action:'reportError')
}
Test:
#Test
void "test save error report"() {
controller.saveReportError()
assertEquals '/reportSiteErrors/reportError', controller.response.redirectUrl
}
I recommend to implement the test as a unit test like this.
import grails.test.mixin.TestFor
import spock.lang.Specification
#TestFor(SimpleController)
class SimpleControllerSpec extends Specification {
void 'test index'() {
when:
controller.index()
then:
response.redirectedUrl == '/simple/hello'
}
}
Using a unit test has the advantage of speed.

Grails Unit Test

I have unit test wich extends GrailsUnitTestCase :
import grails.test.GrailsUnitTestCase
class HttpdParserSpec extends GrailsUnitTestCase {
}
However I saw in Grails documentation that is deprecated.
I tried to use the following :
import grails.test.mixin.TestFor
#TestFor(HttpdParser)
class HttpdParserSpec {
}
I obtain the following error :
Cannot add Domain class [class fr.edu.toolprod.parser.HttpdParser]. It
is not a Domain!
It's true.It's not a Domain class.I only want test a simple class HttpdParser.
What am I doing wrong ?
So how to make a simple unit test ? Have you an example ?
Don't use the TestFor annotation. Just write a unit test as you normally would. TestFor is useful for rigging up Grails artifacts and relevant elements of the environment for unit testing them.
class HttpdParserSpec extends spock.lang.Specification {
void 'test something'() {
when:
def p = new HttpdParser()
p.doSomething()
then:
p.someValue == 42
}
}
You can also just use the #TestMixin annotation with the GrailsUnitTestCaseMixin like this:
import grails.test.mixin.support.GrailsUnitTestMixin
import grails.test.mixin.TestMixin
#TestMixin(GrailsUnitTestMixin)
class MyTestClass {}

Play Framework 2 scala specs2 mockito, how do I write a mocking unit test

So the play framework talks about having specs2 and specs2 having mockito
I want to use mockito to write a test where the template that the controller invokes is a mockito mock.
All the doc's I've found so far are java implementations where you call the mock static function and give it the Mocked class as a generics argument.
From what I can tell the mock function is not exposed by default within a specification, so how do I create a mockito mock?
Please give an example that includes both creating the mock, and asserting the mock is called with certain arguments
After a lot of googling and hair pulling I came up with the following
package test
import org.specs2.mutable._
import play.api.test._
import play.api.test.Helpers._
import org.specs2.mock._
import org.mockito.Matchers
class ToTest {
def go(a:String) = {
"other"
}
}
class MockSpec extends Specification with Mockito {
"Mock" should {
"work" in {
//assemble
val m = mock[ToTest]
m.go(anyString) returns "tested"
//act
val result = m.go("test")
//assert
result must equalTo("tested")
there was one(m).go(Matchers.eq("test"))
}
}
}