mercredi 14 septembre 2016

Mocking a Groovy Service with Spring Boot

I am testing a Spring Boot application that I am writing in Groovy, and I want to mock out one of the @Components.

Were I using plain Java, I would just mock it out with Mockito in a test @Configuration, but that doesn't work with groovy in versions <2.0 (see http://ift.tt/2clv0Le ) and in versions > 2.0, it breaks with Spring (see http://ift.tt/2cqtkwM). Now I'm looking for a workaround--other libraries, a different test design, all are fine.

Here is a standalone example that illustrates what I'm going for (see comment in test):

package testing

import org.junit.Assert
import org.junit.Test
import org.junit.runner.RunWith
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.SpringApplication
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.stereotype.Component
import org.springframework.test.context.junit4.SpringRunner


@SpringBootApplication
public class TheguildRegisterApplication {

    public static void main(String[] args) {
        SpringApplication.run(tech.theguild.TheguildRegisterApplication.class, args);
    }
}

class Account {
    String firstName
    String lastName
}

@Component
class AccountService {

    List<Account> getAllAccounts() {
        return [
                new Account(firstName: "John", lastName: "Doe"),
                new Account(firstName: "Sally", lastName: "Smith")
        ]
    }
}

@RunWith(SpringRunner.class)
@SpringBootTest
class MockTesting {

    @Autowired AccountService accountService

    @Test void test1() {

        // Create Mock Data
        List<Account> employees = [
                [firstName: "The Cat", lastName: "In The Hat"]
        ].collect {d -> d as Account}

        //
        // Replace the data in EmployeeService here with a mock
        //

        Assert.assertEquals(accountService.getAllAccounts().size(), 2)

    }
}

Thanks!

Aucun commentaire:

Enregistrer un commentaire