Grails integration tests with multiple services - unit-testing

What is the best practice to test a Grails Service which depends on another Service?
The default mixin TestFor correctly inject the service under test, for eg:
#TestFor(TopService)
class TopServiceTests {
#Test
void testMethod() {
service.method()
}
}
but if my instance of TopService (service) relies on another Service, like InnerService:
class TopService {
def innerService
}
innerService will not be available, dependency injection doesn't seem to fill this variable. How should I proceed?

Integration tests should not use the #TestFor annotation, they should extend GroovyTestCase. The test annotations are only for unit tests (and will have bad behavior when used in integration tests, especially the #Mock annotations). You're seeing one of those bad behaviors now.
If you extend GroovyTestCase you can then just have
def topService
At the top of your test and it'll get injected with all of it's dependencies injected.
For a unit test case, you'd just want to add new instances of associated services to your service in a setUp method. Just like:
#TestFor(TopService)
class TopServiceTests {
#Before public void setUp() {
service.otherService = new OtherService()
}
...

I have a CustomerRegistrationServiceTest and my CustomerRegistrationService depends on the PasswordService.
my CustomerRegistrationService just autowires it like normal:
class CustomerRegistrationService {
def passwordService
In my CustomerRegistrationServiceTest I have:
#TestFor(CustomerRegistrationService)
#Mock(Customer)
class CustomerRegistrationServiceTests extends GrailsUnitTestMixin {
void setUp() {
mockService(PasswordService)
}
So when I test the CustomerRegistrationService, it is able to access the PasswordService

Related

unable to launch spring-data-rest unit test, RepositoryRestResource not available for #Autowire

I'm porting an app across from JDBC / REST to spring-data-rest and my one and only unit test with fails with the error
NoSuchBeanDefinitionException:
No qualifying bean of type 'com.xxx.repository.ForecastRepository' available
The app was retro-fitted with spring-boot just previously, and now I'm trying to put a new layer in place with spring-data-rest on top of spring-data-jpa.
I'm attempting to work out the correct Java-config according to
Custom Test Slice with Spring Boot 1.4
but I had to deviate from the idiomatic approach because
the #WebMvcTest annotation doesn't suppress the security module which causes the test to fail
the #MockMvcAutoConfiguration fails due to missing dependencies unless I specify #SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK) (see here)
#WebMvcTest and #SpringBootTest are mutually exclusive since they both specify #BootstrapWith and can't run together
So this is the closest I've got but Spring can't locate my #RepositoryRestResource repository:
Repository
#RepositoryRestResource(collectionResourceRel = "forecasts", path = "forecasts")
public interface ForecastRepository extends CrudRepository<ForecastExEncoded,
Long> {
JUnit Test
#RunWith(SpringRunner.class)
#SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK,
classes = {TestRestConfiguration.class})
public class ForecastRestTests {
#Autowired
private MockMvc mockMvc;
#Autowired
private ForecastRepository forecastRepository;
#Before
public void deleteAllBeforeTests() throws Exception {
forecastRepository.deleteAll();
}
#Test
public void shouldReturnRepositoryIndex() throws Exception {
mockMvc.perform(get("/")).andDo(print()).andExpect(status().isOk()).andExpect(
jsonPath("$._links.forecasts").exists());
}
}
Configuration
#OverrideAutoConfiguration(enabled = false)
#ImportAutoConfiguration(value = {
RepositoryRestMvcAutoConfiguration.class,
HttpMessageConvertersAutoConfiguration.class,
WebMvcAutoConfiguration.class,
MockMvcAutoConfiguration.class,
MockMvcSecurityAutoConfiguration.class
})
#Import({PropertySpringConfig.class})
public class TestRestConfiguration {}
Also tried...
I tried to configure the unit test with just #WebMvcTest and this #ComponentScan below from How to exclude AutoConfiguration from Spring Boot), in an attempt to simplify it all, however the excludeFilters had no effect.
#ComponentScan(
basePackages="com.xxx",
excludeFilters = {
#ComponentScan.Filter(type = ASSIGNABLE_TYPE,
value = {
SpringBootWebApplication.class,
JpaDataConfiguration.class,
SecurityConfig.class
})
})
I've set Spring's logging to trace because all I can do at this point is try to find clues as to what is happening from log output. So far though without any luck.
I can see in the logging that RepositoryRestConfiguration is loading, but obviously it isn't fed with the right info and I am unable to work out how that is done, after googling and pouring over the Spring docs and API. I think I must have read every relevant question here on SO .
Update 2016-11-16 10:00
One thing I see in the logs which concerns me is this:
Performing dependency injection for test context [DefaultTestContext#2b4a2ec7 [snip...]
classes = '{class com.xxx.TestRestConfiguration,
class com.xxx.TestRestConfiguration}',
i.e. the context lists the configuration class twice. I specified the config class (once only) on the #SpringBootTest#classes annotation. But if I leave off the #classes from the annotation, Spring Boot finds and pulls in all the config via the #SpringBootApplication class.
So is that a hint that I am specifying the configuration in the wrong place? How else would I do it?
After way too much time, I settled on this approach.
Custom Test Slice with Spring Boot 1.4 looked promising but I couldn't get anywhere with it.
While going over and over
Accessing JPA Data with REST
I realised I had to include the JPA setup because spring-data-rest is using them directly - no chance to mock them or run unit tests without an embedded database.
At least not as far as I understand it. Maybe it is possible to mock them and have spring-data-rest run on the mocks against test data, but I think spring-data-rest and spring-data are probably too tightly coupled.
So integration testing it must be.
In the Spring source code provided with the articles above
gs-accessing-data-rest/ApplicationTests.java
the logging shows Spring Boot pulling in the whole configuration for the application context.
So that my SpringBootApplication class is avoided and the security module isn't loaded up, I set up my tests like this:
#RunWith(SpringRunner.class)
#SpringBootTest
#ContextConfiguration(classes = {
JpaDataConfiguration.class,
TestJpaConfiguration.class,
TestRestConfiguration.class,
PropertySpringConfig.class})
public class ForecastRestTests {
#SuppressWarnings("SpringJavaAutowiringInspection")
#Autowired
private MockMvc mockMvc;
#Autowired
private ForecastRepository forecastRepository;
#Before
public void deleteAllBeforeTests() throws Exception {
forecastRepository.deleteAll();
}
#Test
public void shouldReturnRepositoryIndex() throws Exception {
mockMvc.perform(get("/")).andDo(print()).andExpect(status().isOk()).andExpect(
jsonPath("$._links.forecasts").exists());
}
}
with these configuration classes:
#Configuration
#EnableJpaRepositories(basePackages = {"com.bp.gis.tardis.repository"})
#EntityScan(basePackages = {"com.bp.gis.tardis.type"})
public class JpaDataConfiguration {
and
#Configuration
#OverrideAutoConfiguration(enabled = false)
#ImportAutoConfiguration(value = {
CacheAutoConfiguration.class,
JpaRepositoriesAutoConfiguration.class,
DataSourceAutoConfiguration.class,
DataSourceTransactionManagerAutoConfiguration.class,
HibernateJpaAutoConfiguration.class,
TransactionAutoConfiguration.class,
TestDatabaseAutoConfiguration.class,
TestEntityManagerAutoConfiguration.class })
public class TestJpaConfiguration {}
and
#Configuration
#OverrideAutoConfiguration(enabled = false)
#ImportAutoConfiguration(value = {
RepositoryRestMvcAutoConfiguration.class,
HttpMessageConvertersAutoConfiguration.class,
WebMvcAutoConfiguration.class,
MockMvcAutoConfiguration.class,
MockMvcSecurityAutoConfiguration.class
})
public class TestRestConfiguration {}
so the TL;DR summary is: use #ContextConfiguration to specify the configuration files that specify #OverrideAutoConfiguration and #ImportAutoConfiguration

When using Ninject for dependeny injection is it best practices to use Ninject in your unit tests or use a mocking framework

I am using ninject to inject dependencies in my production environment. I see two options when it comes to writing unit tests. I can either create concrete classes and inject them using ninject, Or I can use a mocking framework like just mock.
My thought process is to just use both and have the deciding factor be whether or not the TestInterface can be constructed in a reusable way. This way we dont waste time writing the same Mocked method to return an empty list over and over again.
Is there a best practice for this type of thing?
With unit tests on class, it doesn't make a lot of sense to include the DI container in the "system under test" (SUT).
by principle, a class unit test should test the class and the class only
usually you can't "reuse" the bindings in the unit test, you have to create them unit-test specific. Therefore you're only re-testing ninject, but not how you're applying it. Ninject is already tested. So no real benefit for you.
If you do acceptance testing / unit testing on component or application level, then it makes perfectly sense to include Ninject in the SUT.
For a class-level unit test one usually takes a dynamic proxy based mocking framework like MOQ or FakeItEasy.
given an implementation:
public interface IDependency {
void Foo(string bar);
}
public class SomeClass
{
private readonly IDependency dependency;
public SomeClass(IDependency dependency)
{
this.dependency = dependency;
}
public void SomeMethod(string arg)
{
this.dependency.Foo(arg);
}
}
a test would look like (xUnit flavor):
public class SomeClassTest
{
private readonly Mock<IDependency> dependency;
private SomeClass testee;
public SomeClassTest()
{
this.dependency = new Mock<IDependency>();
this.testee = new SomeClass(this.dependency.Object);
}
[Fact]
public void SomeMethod_MustPassArgumentToFoo()
{
const string expectedArgument = "AnyArgument;
this.testee.SomeMethod(expectedArgument);
this.dependency.Verify(x => x.Foo(expectedArgument));
}
}
JustMock has NInject built into it plus a mocking container based on it.
Injecting mocks of dependencies is done automatically when you fetch the instance for the first time:
var container = new MockingContainer<ClassUnderTest>();
var testee = container.Instance;
Plus, you can use NInject's syntax for fine-grained control of the injection behavior, as well as JustMock's syntax for configuring mock behavior.

How do I use PowerMock / Mockito / EasyMock to use a mocked object for dependency injection?

I have an AuthenticationManager.authenticate(username,password) method that gets called in someMethod of a SomeService under test. The AuthenticationManager is injected into SomeService:
#Component
public class SomeService {
#Inject
private AuthenticationManager authenticationManager;
public void someMethod() {
authenticationManager.authenticate(username, password);
// do more stuff that I want to test
}
}
Now for the unit test I need the authenticate method to just pretend it worked correctly, in my case do nothing, so I can test if the method itself does the expected work (Authentication is tested elsewhere according to the unit testing principles, however authenticate needs to be called inside that method) So I am thinking, I need SomeService to use a mocked AuthenticationManager that will just return and do nothing else when authenticate() gets called by someMethod().
How do I do that with PowerMock (or EasyMock / Mockito, which are part of PowerMock)?
With Mockito you could just do that with this piece of code (using JUnit) :
#RunWith(MockitoJUnitRunner.class)
class SomeServiceTest {
#Mock AuthenitcationManager authenticationManager;
#InjectMocks SomeService testedService;
#Test public void the_expected_behavior() {
// given
// nothing, mock is already injected and won't do anything anyway
// or maybe set the username
// when
testService.someMethod
// then
verify(authenticationManager).authenticate(eq("user"), anyString())
}
}
And voila. If you want to have specific behavior, just use the stubbing syntax; see the documentation there.
Also please note that I used BDD keywords, which is a neat way to work / design your test and code while practicing Test Driven Development.
Hope that helps.

How to tell PEX to use the mock object when the concrete object is a dependency, and then auto-generate test cases?

I am writing client-side components in a provided framework, and need to be able to unit test my components. The components are written using MVP (Model-View-Presenter) pattern, I want to use PEX to automatically generate unit tests for my presenters.
The following is the code of a presenter.
public partial class CompetitorPresenter : PresenterBase
{
private readonly ICompetitorView _view;
public IGlobalDataAccess GlobalDataAccess;
public IGlobalUI Globals;
public SystemClient Client;
public bool DeleteRecord()
{
if (_view.CompetitorName != "Daniel")
return false;
if (Client.SystemName != "Ruby")
return false;
return true;
}
}
The problem I am having is that the object SystemClient is provided by the framework, and I cannot use a factory class to create an instance of SystemClient. Therefore when I run PEX to automatically generate unit tests, I have to tell PEX to ignore SystemClient, the result of this is that the method DeleteRecord is not fully covered as the line Client.SystemName != "Ruby" is not tested.
Since I have the mock object MSystemClient (created using moles), I am wondering if somewhere in the configuration I could tell PEX to use MSystemClient, and let PEX to automatically generate test cases to fully cover this method.
You are on the right track. If you cannot control where the instance of CompetitorPresenter.Client is created, you can define a mole for all instances:
MSystemClient.AllInstances.SystemNameGet = () => "SomeName";
Your unit test has to be run in a "hosted environment":
[HostType("Moles")]
public void TestMethod()
{
MSystemClient.AllInstances.SystemNameGet = () => "SomeName";
// Test code...
}

Mocking Prism Event Aggregator using Moq for Unit Testing

I need some advice on how to use Moq in a unit test to make sure that my class under test is behaving how I want. That is the class under test publishes an Event Aggregator (from Prism) event and I need some way of asserting that this event has been raised in my test.
I don't have a lot of resource at work and am finding it difficult to know how to set this up.
I have :-
public SomeEvent : CompositePresentationEvent<SomeEvent>
{
EventPayload
}
public SomeClass
{
void Allocate(){EventAggregator.Publish<SomeEvent>}
}
public SomeService : IService
{
SomeService(){ EventAggregator.Subscribe<SomeEvent>(DoSomething)}
void DoSomething(SomeEvent evt){}
}
I think that if my test is for SomeClass I need to verify that if I call SomeClass.Allocate a SomeEvent message is being published. How is this done?
Do I also need to verify that a mocked SomeService is receiving the SomeEvent? Or is that a seperate unit test that belongs to SomeService unit test and not SomeClass?
In any event, not sure how to set any of this up so any advice would be appreciated.
You would supply SomeClass with an IEventAggregator, which will allow you to supply a mock during testing:
public SomeClass(IEventAggregator eventAggregator)
{
_eventAggregator = eventAggregator;
}
Then your test would look something like this:
var fakeEventAggregator = new Mock<IEventAggregator>();
var fakeEvent = new Mock<SomeEvent>();
fakeEventAggregator.
Setup(x => x.GetEvent<SomeEvent>()).
Returns(fakeEvent.Object);
var test = new SomeClass(fakeEventAggregator.Object);
test.Allocate();
fakeEvent.Verify(x => x.Publish(It.IsAny<SomeEventArgs>()));
If these are unit tests then you would test the subscription entirely separately in the SomeService tests. You are testing that SomeClass correctly publishes an event and that SomeService behaves correctly when it is given an event to process.