Grails3 unit test for domain class with derived property - unit-testing

I have the following Domain class with derived property lowercaseTag.
class Hashtag {
String tag
String lowercaseTag
static mapping = {
lowercaseTag formula: 'lower(tag)'
}
}
If I run the following unit test, it will fail on the last line, because lowercaseTag property is null and by default all properties have nullable: false constraint.
#TestFor(Hashtag)
class HashtagSpec extends Specification {
void "Test that hashtag can not be null"() {
when: 'the hashtag is null'
def p = new Hashtag(tag: null)
then: 'validation should fail'
!p.validate()
when: 'the hashtag is not null'
p = new Hashtag(tag: 'notNullHashtag')
then: 'validation should pass'
p.validate()
}
}
The question is how to properly write unit tests in such cases? Thanks!

As I'm sure you've figured out, the lowercaseTag cannot be tested because it's database dependent; Grails unit tests do not use a database, so the formula/expression is not evaluated.
I think the best option is to modify the constraints so that lowercaseTag is nullable.
class Hashtag {
String tag
String lowercaseTag
static mapping = {
lowercaseTag formula: 'lower(tag)'
}
static constraints = {
lowercaseTag nullable: true
}
}
Otherwise, you'll have to modify the test to force lowercaseTag to contain some value so that validate() works.
p = new Hashtag(tag: 'notNullHashtag', lowercaseTag: 'foo')

Related

Is it useless to mock an interface's behavior if it's not to be called in the test

Do i need to mock interfaces that does not call, for instance user name and password field is empty? I'm trying to write test first but confused if mocks should be used.
My login test
private val authRepository: AuthRepository = mockk()
private val userManager: AccountManager = mockk()
private lateinit var authUseCase: AuthUseCase
#BeforeEach
fun setUp() {
clearMocks(authRepository)
clearMocks(userManager)
authUseCase = AuthUseCase(authRepository, userManager)
}
/**
* Scenario: Login check with empty fields:
* * Given I am on the login page
* * When I enter empty username
* And I enter empty password
* And I click on the "Login" button
* * Then I get empty fields error.
*/
#Test
fun `Empty fields result empty fields error`() {
// Given
// When
val expected = authUseCase.login("", "", false)
// Then
verify(exactly = 0) {
authRepository.login(or(any(), ""), or(any(), ""), any())
}
expected assertEquals EMPTY_FIELD_ERROR
}
Do i have to mock interface for the given part of the test or AccountManager even though they are not called since user name and/or fields are empty?
This is the final version of login method i intend to write after tests
class AuthUseCase(
private val authRepository: AuthRepository,
private val accountManager: AccountManager
) {
private var loginAttempt = 1
/*
STEP 1: Throw exception for test to compile and fail
*/
// fun login(
// userName: String,
// password: String,
// rememberMe: Boolean = false
// ): AuthenticationState {
// throw NullPointerException()
// }
/*
STEP3: Check if username or password is empty
*/
// fun login(
// userName: String,
// password: String,
// rememberMe: Boolean = false
// ): AuthenticationState {
//
//
// if (userName.isNullOrBlank() || password.isNullOrBlank()) {
// return EMPTY_FIELD_ERROR
// }else {
// throw NullPointerException()
// }
//
// }
/**
* This is the final and complete version of the method.
*/
fun login(
userName: String,
password: String,
rememberMe: Boolean
): AuthenticationState {
return if (loginAttempt >= MAX_LOGIN_ATTEMPT) {
MAX_NUMBER_OF_ATTEMPTS_ERROR
} else if (userName.isNullOrBlank() || password.isNullOrBlank()) {
EMPTY_FIELD_ERROR
} else if (!checkUserNameIsValid(userName) || !checkIfPasswordIsValid(password)) {
INVALID_FIELD_ERROR
} else {
// Concurrent Authentication via mock that returns AUTHENTICATED, or FAILED_AUTHENTICATION
val authenticationPass =
getAccountResponse(userName, password, rememberMe)
return if (authenticationPass) {
loginAttempt = 0
AUTHENTICATED
} else {
loginAttempt++
FAILED_AUTHENTICATION
}
}
}
private fun getAccountResponse(
userName: String,
password: String,
rememberMe: Boolean
): Boolean {
val authResponse =
authRepository.login(userName, password, rememberMe)
val authenticationPass = authResponse?.authenticated ?: false
authResponse?.token?.let {
accountManager.saveToken(it)
}
return authenticationPass
}
private fun checkUserNameIsValid(field: String): Boolean {
return field.length >15 && field.endsWith("#example.com")
}
private fun checkIfPasswordIsValid(field: String): Boolean {
return field.length in 6..10
}
}
Should i only mock when all other states and passed i get a mock response from repository and interaction with account manager occurs?
What should be given section of the test?
Edit:
I updated given section of this test to
#Test
fun `Empty fields result empty fields error`() {
// Given
every { authRepository.login(or(any(), ""), or(any(), "")) } returns null
// When
val expected = authUseCase.login("", "", false)
// Then
verify(exactly = 0) { authRepository.login(or(any(), ""), or(any(), "")) }
expected assertThatEquals EMPTY_FIELD_ERROR
}
Is there something wrong with this kind of behavior testing?
I would suggest that you don't need the verify in the "Empty fields result empty fields error" test. I would also suggest you write separate tests for each empty field. If you were doing strict TDD you would be testing each condition as you wrote the code. i.e.
'Empty username should error" would be the first test and the first condition tested, then "Empty password should error" the next (after you have done two separate written your second test your code may look like
if (userName.isNullOrBlank()) {
return EMPTY_FIELD_ERROR
}
if (password.isNullOrBlank() {
return EMPTY_FIELD_ERROR
}
Once both the tests above pass you could refactor to
if (userName.isNullOrBlank() || password.isNullOrBlank()) {
EMPTY_FIELD_ERROR
}
Once you start testing the conditional statements for checkUserNameIsValid and checkIfPasswordIsValid, you would need to introduce the authRepository and accountManager to your class (constructor injection) and then you would need to start mocking the calls as you use them. Generally mocking frameworks will fake an object (i.e. the code will run but won't return any meaningful result). You should aim to return actual mock data when you want to test specific behavior i.e. you should be returning a valid object from the authRepository.login when you are testing for a successful login. Generally I stay away from using setup methods in the #BeforeEach and use either a factory method or builder to create my class under test. I am unfamiliar with the kotlin syntax so can at best do some sudo code to demonstrate how your builder or factory functions may look like.
// overloaded factory function
fun create() {
val authRepository: AuthRepository = mockk()
val userManager: AccountManager = mockk()
return AuthUseCase(authRepository, userManager);
}
fun create(authRepository: AuthRepository) {
val userManager: AccountManager = mockk()
return AuthUseCase(authRepository, userManager);
}
fun create(authRepository: AuthRepository, userManager: AccountManager) {
return AuthUseCase(authRepository, userManager);
}
You will need to have a look at how to create a builder in kotlin but the end result you would be looking for is that the builder always starts setting the dependencies for you class under test as mocks that do nothing but allows you to change those mocks.
e.g.
AuthUseCase authUseCase = AuthUseCaseBuilder.Create().WithAuthRepository(myMockAuthRepository).Build();
One final thing. I purposely left out discussing loginAttempt check above as to me it looks like the AuthUseCase is a service class that will be used by multiple users and live for the lifetime of the request in which case you don't want to maintain state within the class (i.e. the loginAttempt variable has the same lifetime as the class). It would be better to record the attempts per username in a database table and the attempt count would need to be reset after each successful login.
Hope this helps.

why are empty strings converted to null passing to the constructor of the domain object in Grails 2.4.0?

I'm new to Groovy and Grails. The Spock test for the domain object to test persist fails due to the empty string being converted to null. Here is the code.
The domain object,
class Todo {
String name
Date createdDate
String priority
String status
static constraints = {
priority blank: true
}
}
The Spock specification,
#TestFor(Todo)
class TodoSpec extends Specification {
void "test persist"() {
when:
new Todo(name: 't1', createdDate: new Date(), priority: "1", status: 'ok').save()
new Todo(name: 't2', createdDate: new Date(), priority: '', status: 'ok').save()
then:
Todo.list().size() == 2
}
}
The result of grails test-app is
Todo.list().size() == 2
| | |
| 1 false
[collab.todo.Todo : 1]
at collab.todo.TodoSpec.test persist(TodoSpec.groovy:18)
I found the empty string '' in the line new Todo(name: 't2', createdDate: new Date(), priority: '', status: 'ok') is converted to null by debugging. After google a while, I see there is a feature in Grails converting the empty strings from the web form to null to persist, which can be disabled by a configuration grails.databinding.convertEmptyStringsToNull = false in the Config.groovy. But I don't think this is the case for Spock UT. I've tried but it doesn't work as I thought.
I was wondering why the empty string is converted to null as a parameter passing to the constructor? Thanks in advance.
It is a little hinky right now, but can be made to work pretty easily. The following test passes with Grails 2.3.9...
A domain class:
// grails-app/domain/com/demo/Person.groovy
package com.demo
class Person {
String title
}
Config.groovy:
// grails-app/conf/Config.groovy
grails.databinding.convertEmptyStringsToNull = false
// ...
A unit test:
// test/unit/com/demo/PersonSpec.groovy
package com.demo
import grails.test.mixin.TestFor
import spock.lang.Specification
#TestFor(Person)
#TestMixin(grails.test.mixin.web.ControllerUnitTestMixin)
class PersonSpec extends Specification {
void "test empty string conversion"() {
when:
def p = new Person(title: '')
then:
p.title == ''
}
}
The key is applying the ContollerUnitTestMixin to the test case, even though it isn't really testing a controller. See https://jira.grails.org/browse/GRAILS-11136.
I hope that helps.
The conversion of empty strings to null is a feature of Grails databinding, so this will happen wherever databinding is used. One such place is when calling the constructor of a domain class with a map argument. If you don't want the string to be converted to null, try this:
new Todo().priority = ''

Having trouble testing model validation with Laravel

I'm just starting out with TDD and I'm trying to test validation in a model. Currently, all my tests pass, but I believe that they shouldn't. The testBodyIsRequiredToValidate() should fail since I have not added it to the rules array. When I remove the title required from the rules array, all my tests fail as expected. However, adding title required causes them all to pass.
My Tests:
class PostTest extends TestCase {
public function testTitleIsRequiredToValidate()
{
$post = new Post;
$post->body = 'foobar';
$this->assertFalse($post->validate(compact('post')));
}
public function testBodyIsRequiredToValidate()
{
$post = new Post;
$post->title = 'foobar';
$this->assertFalse($post->validate(compact('post')));
}
}
My Model:
class Post extends Eloquent {
public function validate($input)
{
$rules = array(
'title' => 'required'
);
$v = Validator::make($input, $rules);
if ($v->passes()) {
return true;
} else {
return false;
}
}
}
This happens because your validation is wrong. You pass the model itself to the validator but you should pass an associative array.
When you delete title from the rules you pass an empty rule, so the validation will be always true, thats why all your test fail.
When you add title to your rules, the validations will be always false hence all your tests pass, because the validator's first parameter doesn't have an array element called title.
One way to correct this is to change your validation line to this:
$v = Validator::make(array('title' => $input['post']->title), $rules);
Here you get the $post from your $input array, because compact() will put it to an array with the key of the variable name. Then you access the title property of the object and make this to the value of the title key so the validator will be able to find and validate it.
I have to mention that your validation technique is kinda bad for me. You pass the object in an array to a function of the same object. Why don't you get the object in the function?
I would write the validator function like this:
public function validate() {
$rules = array(
'title' => 'required'
);
$v = Validator::make($this->toArray(), $rules);
return $v->passes();
}
So I could call the function like this in the tests:
$this->assertFalse($post->validate());

how to unit test grails' message tag

in the controller there is an action:
def delete = {
withDomain {
it.delete()
flash.message = "${message(code: 'default.deleted.message', args: [message(code: 'chocolateBar.label', default: 'ChocolateBar'), it.name])}"
redirect action: 'list'
}
}
which can be tested in development. while in unit test, the message(..) method throws exception ( groovy.lang.MissingMethodException: No signature of method: longtest.ChocolateBarController.message() is applicable for argument types: (java.util.LinkedHashMap) values: [[code:chocolateBar.label, default:ChocolateBar]]):
public void testDelete() {
controller.params.id = '3'
controller.delete()
assert 'list'==controller.redirectArgs.action
}
After study, a mockTagLib method should be called during setup. But found no correct class name for built-in message(..). Please help.
I've solved the problem in unit controller test. like this:
//This is inside Spock test
#Shared
ResourceBundleMessageSource messageSource = null
#Shared
Closure mockMessage = {Map map ->
return messageSource.getMessage((String)map.code, (Object[])map.args, Locale.default)
}
def setupSpec(){
URL url = new File('grails-app/i18n').toURI().toURL()
messageSource = new ResourceBundleMessageSource()
messageSource.bundleClassLoader = new URLClassLoader(url)
messageSource.basename = 'messages'
messageSource.setDefaultEncoding("utf-8")
}
def setup(){
controller.metaClass.message = mockMessage
}
This code is for spock test, but main idea is also available for normal grails test.
In running phase(not test),
calling "message" in controller class results in calling "message" of ValidationTagLib class,
but they are not bind in unit test phase.
So I made almost same logic of "message" of ValidationTagLib,
and bind it(named "mockMessage") to controller.message.
With this code, you can execute "message" correctly in controller class in test.

Unit testing custom validator of command object with dependency

I have a command object for registering user, and I want to check how old is the user. This command object has a service dependency. How can I test custom validator for my dateOfBirth property? As it looks now is taken straight from documentation, here.
class RegisterUserCommand {
def someService
String username
String password
String password2
String email
Date dateOfBirth
static constraints = {
// other constraints
dateOfBirth blank: false, validator: {val, obj ->
return obj.someService.calculateAge(val) >= 18
}
}
So basically the question is: how can I mock 'obj' parameter of the validator closure?
The easiest way to test validation on a command object is to use GrailsUnitTestCase.mockForConstraintsTests. A mock validate method will be applied to your command object, and you can just call validate() like you would outside of a test.
Here's an example of how you could write your unit test. The blank constraint isn't meaningful for dates, so I've changed it to nullable: false.
import grails.test.GrailsUnitTestCase
class RegisterUserCommandTests extends GrailsUnitTestCase {
RegisterUserCommand cmd
protected void setUp() {
super.setUp()
cmd = new RegisterUserCommand()
mockForConstraintsTests RegisterUserCommand, [cmd]
}
void testConstraintsNull() {
cmd.dateOfBirth = null
cmd.someService = [calculateAge: { dob -> 18 }]
def result = cmd.validate()
assert result == false
assert cmd.errors.getFieldErrors('dateOfBirth').code == ['nullable']
}
void testConstraintsCustom() {
cmd.dateOfBirth = new Date()
cmd.someService = [calculateAge: { dob -> 17 }]
def result = cmd.validate()
assert result == false
assert cmd.errors.getFieldErrors('dateOfBirth').code == ['validator.invalid']
}
}
Note that your service won't get injected in a unit test (it will in an integration test though), so you'll either need to mock it, as above, or create an instance and assign it to cmd.someservice.