Junit method invocation fails due to spring injection - java

I have written Junit test class to test particular method. One of the variables being processed in this method is spring injected, by taking the value from properties file.
Below is my test method
#Test
public void myTestMethod() {
//invoking the method to be tested
Assert.assertTrue(updateGroceries());
}
This is the class to be tested,
public class ToBeTested {
//Spring injected value
String categories;
public boolean updateGroceries() {
List<String> categoryList = StringUtils.convertStringToList(categories);
}
In the above class, categories variable is spring injected.
This is properties file content:
categories = Dals,Pulses,Dry Fruits,Edible Oil
Now while running my Junit method, execution is failing because dependency injection is failing.Since the code I want to test runs on tomcat. I want to test the code without running tomcat. Please suggest some solution.

First of all to run mockito you need to enable it over your test.
Using annotation #RunWith(MockitoJunitRunner.class) or execute at the beginning of your test Mockito.initMocks().
Then your test should look like:
#RunWith(MockitoJunitRunner.class)
private YourTest{
#InjectMocks
ToBeTested toBeTested;
#Mock
ToBeTestedDependency dependency;
#Before
public void setUp(){
ReflectionTestUtils.setField(toBeTested, "categories",
"someCategory");
}
#Test
public void shouldDoThisOrThat(){
toBeTested.updateCategories();
}
}
Unfortunately mockito doesn't support injecting #Valueannotated field. You need to use ReflectionTestUtils or setup run your test with SpringJUnit4ClassRunner where you need to define your spring context with PropertyPlaceholder configuration to resolve property that you have as your Value key. There you can find reference to documentation and example of spring testing approach.
Hope this helped.

You should look at Mockito. When you use mockito framework, you can create mocks for spring injected values. You should read more on mockito website.

Related

Getting NullPointerException tracer.currentSpan() is Null

I'm trying to create test case for given class and want to return traceId value but getting trace.currentSpan() is null.
Here is my Class
public class ConsumerService{
private final Tracer tracer;
#Autowired
private RequestService requestService;
public void consumerProductionRequest(DisclaimerRequest disclaimerRequest){
String traceId=tracer.currentSpan.context().traceId();
log.info(traceId);
if(disclaimerRequest.getReqId()==null){
disclaimerRequest.setReqId(UUID.randomUUID().toString());
}
}
}
//Test Class
#ExtendWith(MockitoExtension.class)
class ConsumerServiceTest{
#InjectMocks
ConsumerService consumerService;
#Autowired
Tracer tracer;
#Test
void Test(){
Tracer tracer=Mockito.mock(Tracer.class);
String traceId;
Mockito.when(tracer.currentSpan().context.traceId()).thenReturn(traceId);
DisclaimerRequest disclaimerRequest=new DisclaimerRequest();
consumerService.consumerProductionRequest(disclaimerRequest);
}
}
Why am I getting tracer.currentSpan() null. I'm using JUnit 5 and new in this. Please someone help me to solve this.
Here, in your test class:
#Autowired
Tracer tracer;
Turn that into
#Mock
Tracer tracer;
(and add the corresponding import to Mockito). You want that Mockito creates a mock object, and then inserts that into your object under test. Also note that your test method itself redefines tracer, thus shadowing whatever else you did on class level. Therefore that spec for tracer within the test method won't have any effect on the mocked Tracer instance that already got injected into your object under test.
Tracer tracer=Mockito.mock(Tracer.class);
String traceId;
Mockito.when(tracer.currentSpan().context.traceId()).thenReturn(traceId);
tracer will be mock and you can see it in debug or just simply print it.
also each method returns null because you didn't specify which method will return value because spring context does not work in unit tests. In integration tests you can autowire it.
Mockito.when(tracer.getCurrentSpan()).thenReturn(someSpan);
Mockito.when(tracer.getCurrentSpan().getContext()).thenReturn(someContext);
String traceId;
Mockito.when(tracer.currentSpan().context.traceId()).thenReturn(traceId);
You have to mock getCurrentSpan and getContext methods that will solve your problem. Also you can not autowire it just use #Mock annotation. Spring context does not exist in unit tests so it won't be autowired. Spring related codes won't work. Integration test runs the spring context for you and you can autowire it.

Injecting non-mocks defined by a #Configuration class into a unit test

Java 8, JUnit 4 and Spring Boot 2.3 here. I have a situation where I have a #Component-annotated Spring Boot class that gets #Autowired with all its dependencies (the beans are defined in a #Configuration-annotated config class):
#Configuration
public class SomeConfig {
#Bean
public List<Fizz> fizzes() {
Fizz fizz = new Fizz(/*complex logic here*/);
return new Collections.singletonList(fizz);
}
#Bean
public Buzz buzz() {
return new Buzz(/*complex logic here*/);
}
}
#Component
public class ThingDoerinator {
#Autowired
private Lizz<Fizz> fizzes;
#Autowired
private Buzz buzz;
public String doStuff() {
// uses fizz and buzz extensively inside here...
}
}
I can easily write a unit test to inject all of these dependencies as mocks:
public class ThingDoerinatorTest extends AbstractBaseTest {
#Mock
private List<Fizz> fizzes;
#Mock
private Buzz buzz;
#InjectMocks
private ThingDoerinator thingDoerinator;
#Test
public void should_do_all_the_stuff() {
// given
// TODO: specify fizzes/buzz mock behavior here
// when
String theThing = thingDoerinator.doStuff();
// then
// TODO: make some assertions, verify mock behavior, etc.
}
}
And 80% of the time that works for me. However I am now trying to write some unit tests that are more like integration tests, where instead of injected mocks, I want the beans to be instantiated like normal and get wired into the ThingDoerinator class like they would be in production:
public class ThingDoerinatorTest extends AbstractBaseTest {
#Mock
private List<Fizz> fizzes;
#Mock
private Buzz buzz;
#InjectMocks
private ThingDoerinator thingDoerinator;
#Test
public void should_do_all_the_stuff() {
// given
// how do I grab the same Fizz and Buzz beans
// that are defined in SomeConfig?
// when -- now instead of mocks, fizzes and buzz are actually being called
String theThing = thingDoerinator.doStuff();
// then
// TODO: make some assertions, verify mock behavior, etc.
}
}
How can I accomplish this?
You can use SpringBootTest.
#SpringBootTest(classes = {Fizz.class, Buzz.class, ThingDoerinator.class})
#RunWith(SpringRunner.class)
public class ThingDoerinatorTest {
#Autowired
private Fizz fizz;
#Autowired
private Buzz buzz;
#Autowired
private ThingDoerinator thingDoerinator;
}
You don't need to mock anything, just inject your class in your test and your configuration will provide the beans to your ThingDoerinator class and your test case will work as if you are calling the ThingDoerinator. doStuff() method from some controller or other service.
TL;DR
I think, you are confused with tests running whole spring context and unit test which just test the function/logic we wrote without running whole context. Unit tests are written to test the piece of function, if that function would behave as expected with given set of inputs.
Ideal unit test is that which doesn't require a mock, we just pass the input and it produces the output (pure function) but often in real application this is not the case, we may find ourselves in situation when we interact with some other object in our application. As we are not about to test that object interaction but concerned about our function, we mock that object behaviours.
It seems, you have no issue with unit test, so you could mock your List of bean in your test class ThingDoerinator and inject them in your test case and your test case worked fine.
Now, you want to do the same thing with #SpringBootTest, so I am taking a hypothetical example to demonstrate that you don't need to mock object now, as spring context will have them, when #springBootTest will load whole context to run your single test case.
Let's say I have a service FizzService and it has one method getFizzes()
#Service
public class FizzService {
private final List<Fizz> fizzes;
public FizzService(List<Fizz> fizzes) {
this.fizzes = fizzes;
}
public List<Fizz> getFizzes() {
return Collections.unmodifiableList(fizzes);
}
}
Using constructor injection here1
Now, my List<Fizzes would be created through a configuration (similar to your case) and been told to spring context to inject them as required.
#Profile("dev")
#Configuration
public class FizzConfig {
#Bean
public List<Fizz> allFizzes() {
return asList(Fizz.of("Batman"), Fizz.of("Aquaman"), Fizz.of("Wonder Woman"));
}
}
Ignore the #Profile annotation for now2
Now I would have spring boot test to check that if this service will give same list of fizzes which I provided to the context, when it will run in production
#ActiveProfiles("test")
#SpringBootTest
class FizzServiceTest {
#Autowired
private FizzService service;
#Test
void shouldGiveAllTheFizzesInContext() {
List<Fizz> fizzes = service.getFizzes();
assertThat(fizzes).isNotNull().isNotEmpty().hasSize(3);
assertThat(fizzes).extracting("name")
.contains("Wonder Woman", "Aquaman");
}
}
Now, when I ran the test, I saw it works, so how did it work, let's understand this. So when I run the test with #SpringBootTest annotation, it will run similar like it runs in production with embedded server.
So, my config class which I created earlier, will be scanned and then beans created there would be loaded into the context, also my service class annotated with #Service annotation, so that would be loaded as well and spring will identify that it needs List<Fizz> and then it will look into it's context that if it has that bean so it will find and inject it, because we are supplying it from our config class.
In my test, I am auto wiring the service class, so spring will inject the FizzService object it has and it would have my List<Fizz> as well (explained in previous para).
So, you don't have to do anything, if you have your config defined and those are being loaded and working in production, those should work in your spring boot test the same way unless you have some custom setup than default spring boot application.
Now, let's look at a case, when you may want to have different List<Fizz> in your test, in that case you will have to exclude the production config and include some test config.
In my example to do that I would create another FizzConfig in my test folder and annotate it with #TestConfiguration
#TestConfiguration
public class FizzConfig {
#Bean
public List<Fizz> allFizzes() {
return asList(Fizz.of("Flash"), Fizz.of("Mera"), Fizz.of("Superman"));
}
}
And I would change my test a little
#ActiveProfiles("test")
#SpringBootTest
#Import(FizzConfig.class)
class FizzServiceTest {
#Autowired
private FizzService service;
#Test
void shouldGiveAllTheFizzesInContext() {
List<Fizz> fizzes = service.getFizzes();
assertThat(fizzes).extracting("name")
.contains("Flash", "Superman");
}
}
Using different profile for tests, hence #ActiveProfile annotation, otherwise the default profile set is dev which will load the production FizzConfig class as it would scan all the packages ( 2Remember the #Profile annotation above, this will make sure that earlier config only runs in production/dev env ). Here is my application.yml to make it work.
spring:
profiles:
active: dev
---
spring:
profiles: test
Also, notice that I am importing my FizzConfiguration with #Import annotation here, you can also do same thing with #SpringBootTest(classes = FizzConfig.class).
So, you can see test case has different values than in production code.
Edit
As commented out, since you don't want test to connect to database in this test, you would have to disable auto configuration for spring data JPA, which spring boot by default does that.
3You can create a another configuration class like
#Configuration
#EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class, HibernateJpaAutoConfiguration.class})
public TestDataSourceConfiguration {}
And then include that with your #SpringBootTest, this will disable default database setup and then you would be left with last piece of puzzle which is any repository interaction you might be having in your class.
Because now, you don't have auto configuration in your test case, those repository are just interfaces, which you can easily mock inside your test class
#ActiveProfiles("test")
#SpringBootTest
#Import(FizzConfig.class, TestDataSourceConfiguration.class)
class FizzServiceTest {
#MockBean
SomeRepository repository;
#Autowired
private FizzService service;
#Test
void shouldGiveAllTheFizzesInContext() {
// Use Mockito to mock behaviour of repository
Mockito.when(repository.findById(any(), any()).thenReturn(Optional.of(new SomeObject));
List<Fizz> fizzes = service.getFizzes();
assertThat(fizzes).extracting("name")
.contains("Flash", "Superman");
}
}
1Constructor injection is advisable instead of `#Autowired` in production code, if your dependencies are really required for that class to work, so please avoid it if possible.
3Please note that you create such configuration only in test package or mark with some profile, do not create it in your production packages, otherwise it will disable database for your running code.

Spring dependencies not being injected into BeforeSuite method?

I am running a spring boot application that uses TestNG as the testing framework. My tests are set up like this:
A parent class, which is in charge of setup logic and takes care of all of the configuration stuffs:
#ContextConfiguration(classes = {TestingConfig.class}, initializers = ConfigFileApplicationContextInitializer.class)
#ContextConfiguration(classes = TestConfig.class)
#TestPropertySource(locations = "classpath:application.yml")
public abstract ParentTestClass extends AbstractTestNGSpringContextTests {
#Autowired
private ServiceClient serviceClient;
#BeforeSuite
public void beforeClass() {
Assert.assertNotNull(serviceClient);
serviceClient.doSomeSetupWork();
}
}
There are multiple child test classes. Each on inherits form the parent test class so that they share the same setup logic.
public ChildTestClass1 extends ParentTestClass {
#Test
public void someTest() {
...
}
// More tests not shown
}
public ChildTestClass2 extends ParentTestClass {
#Test
public void anotherTest() {
...
}
// More tests not shown
}
The serviceClient is a client for one of the web services that the test suite depends on. I am making calls with the service client to set up the data in the other service before running the test cases.
The problem is this: previously I was using the #BeforeClass annotation, which meant that the parent class's setup method was being run once for every child test class. This was ok, but it was really slow waiting for the same setup to be run multiple times.
So I thought to myself: I'll just change the #BeforeClass annotations in the ParentTestClass to be #BeforeSuite instead! That will solve all of my problems!
Wrong.
Now when I run it, the Assert.assertNotNull(serviceClient); line in the beforeClass() method of the parent class fails. In short, Spring dependencies aren't being injected into the #BeforeSuite annotated method, even tho they were being injected in the method when it was annotated with #BeforeClass.
Any thoughts here? I'd really appreciate it!
I believe this is working as designed. From looking at how the implementation is built within org.springframework.test.context.testng.AbstractTestNGSpringContextTests (from which you extend), the dependencies are injected into your test class via the org.springframework.test.context.support.DependencyInjectionTestExecutionListener#injectDependencies (this is a listener).
All the listeners including the DependencyInjectionTestExecutionListener is invoked only via org.springframework.test.context.testng.AbstractTestNGSpringContextTests#springTestContextPrepareTestInstance which is a #BeforeClass(alwaysRun=true) classified method.
So your dependencies aren't available to you until and unless this #BeforeClass annotated method runs to completion. So you would have to move out your #BeforeSuite method and have it work with a #BeforeClass annotation only.
If you don't need your service setup to be done multiple times, then you would need to add an edit check in your test code that does the setup ONLY IF ITS NOT DONE.
Here is the solution to all your problem.
#Override
#BeforeSuite
protected void springTestContextPrepareTestInstance() throws Exception {
super.springTestContextPrepareTestInstance();
}
Hope this helps you to inject the dependencies.

Mocking aspects, testng and spring 4

I have a very basic scenario where I just need to call a method which has an annotation. This annotation simply calls an AspectJ advice. I just need to make sure that the advice is being called, ideally via a mock verify. Tests are being run using TestNG and mocking using Mockito. Spring is version 4.
class under test
public class MyClassUT
{
#MyAnnotation
public myMethod...
{
...
}
}
test class
#ContextConfiguration(classes = {SpringTestConfig.class})
#WebAppConfiguration
public class MyClassUtTest extends AbstractTestNGSpringContextTests
{
#InjectMocks private MyClassUT mine;
#BeforeMethod
public void init()
{
MockitoAnnotations.initMocks(this);
}
#Test
public void testMyMethod()
{
mine...
}
}
The problem is that the advice is being called and everything is OK, except for the fact that the advice class is instantiated once by spring and another time before calling the said method. The instance being used is the latter which of course has no dependencies injected so it fails. What I am trying to do is provide spring with a mock of my advice or at least inject a mock of the service it depends on and ask AspectJ to use that existing instance.
I have tried using factory methods for the advice, spring test configurations etc, however nothing seems to be working. I have tried also with EnableAspectJautoproxy to no avail, instantiated the aspect with a #Bean annotation, also as a factory method - but nothing works well unfortunately.
(It is also interesting to note that when I enable AspectJ in eclipse, the aspect test also run in maven and as far as I know, nothing changes in pom.xml.)
So, my question is:
How do I make the test use an instance of the aspect I or spring create so that when the method MyMethod is called, its dependencies are in place , or the mock version is used?
This problem is basically equivalent,
but
How do I do this without a single line of XML config - I've seen using an apectOf factory method config being mentioned a lot, but I need a pure annotation solution, if possible;
Works with TestNg not JUnit;
Thank you!

Mocking local object created by spring application context using Mockito

I am trying to mock a local object, using Mockito Framework, that is being created from the spring application context; But every time I run the application its fails to replace the original object with the mocked object.
Here is the original class's code spinets:
public void executeMyJob(){
ApplicationContext springContext = ApplicationContextUtil.getApplicationContext();
MusicEAO music= (MusicEAO) springContext.getBean("MusicEAO");
List<Brand> dataList =music.getAll();
......
}
I want to mock the MusicEAO so when the getAll() method is called, it will use the mock object.
Below is my test class code snippets:
#Mock
MusicEAO musicEAO;
when(musicEAO.findAll()).thenReturn(myDefinedList);
How can I resolve this issue?
It's hard to tell from the cod you posted but the problem might be that you are mocking MusicEAO in your test but the code you are executing is using a Spring ApplicationContext to get a reference to the MusicEAO bean.
Your original class should not use MusicEAO music= (MusicEAO) springContext.getBean("MusicEAO"); but instead have the bean injected by Spring using #Autowired through a constructor or a setter method (or other dependency injection method). You test will then be able to easily inject a mock version.
class MyJobClass {
MusicEAO music;
#Autowired
public MyJobClass(MusicEAO musicEao) {
this.music = musicEao;
}
public void executeMyJob(){
List<Brand> dataList =music.getAll();
......
}
}
When you say
every time I run the application it fails to replace the original
object with the mocked object
You shouldn't have to run the application to run a unit test for this class - are you asking how to inject mocks into a running application?
.
It doesn't work this way. In your current code :
The following instance is the one in your test :
#Mock MusicEAO musicEAO;
But in your production code, you are using Spring to acquire the Music instance :
MusicEAO music= (MusicEAO) springContext.getBean("MusicEAO");
Nowhere you seem to say to spring that you want the Music mock to be affected to MusicEAO bean name.
If you are doing a Unit Test I would recommand you to avoid messing with Spring, if that's an integration test, then you'll have to find a way to create the mock and pass it over to spring.
For example you can create the mock in the Spring context, autowire it in your test.
Also, I wouldn't recommand the use of static calls in this situation to acquire the Spring context in order to finaly get a hold on the Music object. it makes me think of Spring as a registry which isn't really the case. Spring is a container. Instead you should try to refactor your code in such a way that the Music bean is wired (#Autowired, setters, etc.) in ExecutionJob.
Then it would be even easier to write a Unit Test with JUnit and Mockito, with annotations like #Mock and #InjectMocks.
Hope that helps.

Categories

Resources