TestNG + Spring + Power mock Unit test - spring

I have a Spring based application and am in the process of unit testing it. I'm using TestNG for unit tests. For my test i need to make use of PowerMockito to mock some static methods. I also need to make use of a test spring config file for only my unit test.
I'm unable to write my unit tests combining all the three i.e. TestNg, PowerMock and Spring.
I can combine TestNG and Spring by extending the class AbstractTestNGSpringContextTests, however cant mock static methods, instead it executes the actual static method. Something like the below:
#PrepareForTest(MyUtils.class)
#ContextConfiguration(locations = { "classpath:config/test-context.xml"})
public class MyImplTest extends AbstractTestNGSpringContextTests{
.....
}
I can combine TestNG with PowerMockito by extending the class PowerMockTestCase. But then the test spring config files are not resolved. Something like the below:
#PrepareForTest(MyUtils.class)
#ContextConfiguration(locations = { "classpath:config/test-context.xml"})
public class MyImplTest extends PowerMockTestCase{
.....
}
Is there any way for me to write my unit tests combining all the three, i.e. TestNg, PowerMockito and Spring context?

Rather than extending PowerMockTestCase, have you tried using the PowerMockObjectFactory by writing a method like below? Then you can extend AbstractTestNGSpringContextTests.
#ObjectFactory
public IObjectFactory getObjectFactory() {
return new org.powermock.modules.testng.PowerMockObjectFactory();
}
This is suggested by the Powermock GitHub docs.

Related

Run custom ApplicationContextInitializer in #SpringBootTest

i try to run a custum ApplicationContextInitializer within an integration test which is annotated with #SpringBootTest. I've tried to use a combination of #SpringBootTest and #ContextConfiguration, which looks like this:
#SpringBootTest
#ContextConfiguration(
initializers = CustomContextInitializer.class
)
public class Test {
....
}
This fails because some bean construction triggered by #SpringBootTest, depends on properties which will be injected by programmaticaly logic of my CustomContextInitializer and this one is executed parallel so that this properties aren't available at this point.
Is there a solution for this situation? Could the CustomContextInitializer run before the initalisation procedure triggered by #SpringBootTest?

Unable to run spring-boot-test

I am new to Spring-boot.
We are trying to practice spring-boot-test by adding the following Java class in this Spring guide for testing purpose.
However, it turns out that we are not able to trigger this Java class. In other words, there is no any test result showing up in the our eclipse console.
Could someone suggest us where we do wrong?
Thanks!
GreetingControllerTest.java
package hello;
#RunWith(SpringJUnit4ClassRunner.class)
#SpringApplicationConfiguration(classes = Application.class)
#WebAppConfiguration
#IntegrationTest
public class GreetingControllerTest {
private RestTemplate restTemplate = new RestTemplate();
#Test
public void testGreeting() {
System.out.println("Where is my TEST?????!!!!!!");
String url = "http://localhost:8080/greeting";
assertNotNull(restTemplate.getForObject(url, Greeting.class));
}
}
The Spring Framework does not run (trigger) tests. Rather, a testing framework like JUnit or TestNG runs tests.
Your code appears to be fine. So, assuming that the example you supplied compiles (i.e., has the correct package imports) and assuming that the #Test annotation you have declared is #org.junit.Test, then you simply need to run the test as a JUnit test.
Your IDE (e.g., Eclipse, IntelliJ, NetBeans) and build framework (e.g., Maven, Ant, Gradle) should provide support for running JUnit tests.
Regards,
Sam

What does this do: #RunWith(SpringJUnit4ClassRunner.class)

What does this annotation do?
When would I want to use it?
When would I not want to use it?
#RunWith(SpringJUnit4ClassRunner.class)
I can find more usages of this when I Google and do not find a 101 explanation as to what this annotation is supposed to communicate to me or when/why I would use it?
The annotation is used to configure a unit test that required Spring's dependency injection.
From Spring Reference - 10. Unit Testing:
10.1 Creating a Unit Test Class
In order for the unit test to run a batch job, the framework must load the job's ApplicationContext. Two annotations are used to trigger this:
#RunWith(SpringJUnit4ClassRunner.class): Indicates that the class should use Spring's JUnit facilities.
#ContextConfiguration(locations = {...}): Indicates which XML files contain the ApplicationContext.
If you are using annotations rather than XML files, then any class that you are unit testing that requires Spring dependency injection needs to be put into the #ContextConfiguration annotation. For example:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = FooManager.class)
class FooManagerTest {
#Autowired
FooManager fooManager;
Now when you use fooManager in a unit test it will have have a Spring context setup for it.
If fooManager autowires in any beans then those bean's classes also need to be in the #ContextConfiguration annotation. So if fooManager autowires in a FooReporter bean:
#ContextConfiguration(classes = {FooManager.class, FooReporter.class})
If the beans that fooManager autowires in contain state, then you will likely want to reset the state of those beans for each test. In that case you can add the #DirtiesContext annotation to your test class:
#DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
If fooManager or any of its autowired beans reads Spring config then you need to add an initializers list to the #ContextConfiguration annotation, that contains the ConfigFileApplicationContextInitializer class:
#ContextConfiguration(classes = {FooManager.class, FooReporter.class}, initializers = ConfigFileApplicationContextInitializer.class)
To answer the when you would and wouldn't want to use it part of the question.
When to use SpringJUnit4ClassRunner
IMO SpringJUnit4ClassRunner should be used very sparingly. There is a significant overhead involved with starting up a Spring container to run a unit test.
I typically use SpringJUnit4ClassRunner to test:
that components are injected (auto-wired) as expected
that configuration data is injected as expected
When you are injecting components issues can arise if the #Qualifier annotation is not used or used incorrectly, for example.
When loading configuration from multiple yaml files you may want to test that maps are being merged as expected, with the appropriate overrides occurring.
At the very least I always have a simple SpringJUnit4ClassRunner test as a sanity check that the Spring container starts up OK.
When not to use SpringJUnit4ClassRunner
I would not use SpringJUnit4ClassRunner to test the non-Spring related functionality in my code under test. Which in my experience means most of the functionality.
So this means that any autowired components and injected config data needs to be mocked. This can mean quite a bit of setup code for your unit tests. However this setup code only needs to be written once for all the tests in your class under test. It is also much quicker to run unit tests with mocked components.
I keep the mocking simple and use Spock to mock the components. Example groovy code:
import spock.lang.Specification
class FooManagerTest extends Specification {
FooManager cut
void createMockFooReporter() {
FooReporter mockFooReporter = Mock(FooReporter)
mockFooReporter.fooFormatter = Mock(FooFormatter)
}
void setup() {
cut = new FooManager()
cut.fooReporter = createMockFooReporter()
}
void "Basic test"() {
// Do a basic test using 'cut'
}
}
In this example the class under test FooManager has an autowired FooReporter which itself contains an autowired FooFormatter.
I think #RunWith annotation is in order to initialize the context of spring. Because the junit5 is released, you just can replace it with #SpringJUnitConfig.By the way, #RunWith annotation is already replaced by #ExtendWith, but you still can use it.

Mock-service and Grails jaxrs integration test

I want to test a grails application(using jaxrs) and it's integrations. For this task I hope to use the awesome IntegrationTestCase-class from the jaxrs plugin.
This is challenging because I want to mock/replace a service within my application. With “pure” Spring I would create testcontext and manually wire up the mock. I have no idea how to do this in grails.
I’ve tried to access the ApplicationContext directly
Holders.grailsApplication.mainContext.registerMockBean("myService", new MyMock())
This does not seem to work as the mock is not used during the test. Any ideas?
Try to define in test class his way:
#Before
void before() {
Holders.grailsApplication = grailsApplication
defineBeans {
myService(MyMock)
}
}
It's for jUnit tests. If you use Spock, rename before() to setup() and see Spock basics Fixture Methods.

Using Spring #ActiveProfile in integration tests

I am using #Profile Spring annotations to choose between embedded, standalone and container managed data sources. In order to choose 'embedded' my integration tests are annotated to activate the appropriate profile:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(loader=AnnotationConfigContextLoader.class, classes={TestConfigWrapper.class})
#ActiveProfiles({"EMBEDDED_DB"})
public class SomeIntegrationTest {
The problem is that I would like to move '#ActiveProfiles' into TestConfigWrapper, but doing this doesn't get picked up and the application context won't load any DataSources.
This means I have to annotate every integration test with an #ActiveProfile which effectively means it becomes integration test boiler-plate and could easily hamper future refactoring.
Is there a way I can do this using java config?
Per comment from Hippooom use an abstract class to configure tests:
#WebAppConfiguration
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes={WebAppInitializer.class})
#ActiveProfiles({Profiles.EMBEDDED_DB})
public abstract class ProfiledIntegrationTest {
}

Resources