I am trying to run a Junit test case for a method which uses webapplication context internally. However my problem is that I can not create or mock WebApplicationContext in Junit. When application is build and run then the actual code executes fine and webapplication context is created but in Junit it can not create the same.
My test case has below tags
#WebAppConfiguration
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration("classpath:applicationcontext.xml")
The method which I am trying to test has below code
WebApplicationContext context =
ContextLoader.getCurrentWebApplicationContext();
context.getBean("checkStatus", checkStatus.class);
At this point I get null pointer exception as it can not get webapplication context from ContextLooader, Can I mock this some how so that it does not give null pointer or some how can I get the actual webapplication context so that I can use it.
Should I add some code for WebApplicationContext loading in my application context xml file. In my web.xml file there is an entry regarding ContextLoaderListener should I read configuration from web.xml also in my Junit Test case?
Please provide some suggestion.
there's a lot missing from you question, including details of your environment, version numbers, and especially the exact problem you're trying to solve.
we run junit and spring boot flawlessly using the instructions in https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html#boot-features-testing-spring-boot-applications-testing-with-running-server .
but since we have no information about your use case, i can't tell whether that would work for you or not.
Related
I'm writing integration tests using MockMvcBuilders.webAppContextSetup() in JUnit 5.
I'm extending with Sam Brannen's SpringExtension and a MockitoExtension. (Really, I'm using the composed SpringJUnitJupiterWebConfig)
I get this output when running the tests (edited):
java.lang.IllegalStateException: Failed to load ApplicationContext
BeanDefinitionStoreException: Failed to process import candidates for configuration class [com.example.myapp.config.SomeConfig];
Could not resolve placeholder 'someEnvVar' in string value "classpath:/com/example/myapp/config/${someEnvVar}/custom.properties"
(This is in an internal company library on which my application depends.)
Seems clear that I need to set the environment property before the container starts up. But I'm struggling to discover how to hook into that with JUnit5.
I want to add PropertySources to the environment, I assume, but to get the environment, I have to get the application context, and in so doing, it instantiates, erroring out before I can do anything with it.
I tried creating my own extension and getting a handle to the environment during the BeforeAllCallback.
I'm getting the feeling that I'm going about it all wrong and I'm missing something fundamental.
I just needed to use the #TestPropertySource annotation on my test class.
I created a tutorial that incorporates various components of J2EE in them. The app is an ear module that has an ejb project and a web project.
the project structure is
john-app
john-ear
john-ejb
john-web
the ejb project has a couple dao that perform basic crud operations using jpa. I'm trying to learn/understand jax-rs to gain a better understanding of json and handling json objects. the project is loosly based on
this project:
http://www.developer.com/java/creating-restful-web-services-with-jax-rs.html
so, i created my BookResource here and made it a stateless ejb. i have everything compiling and deploying without any obvious errors - other parts of the app work (the jpa stuff) but i can't get the jax-rs stuff to
work. i have a couple of"Books" that I created in my database and am wanting to test this by making a rest call through the browser.
so i deploy my .ear file in wildfly (v10) with no obvious errors, I see JNDI mappings for my EJB's...etc
initially, i'd like to be able to test this through my browser, but am not certain what url to use -- the class i have extending javax.ws.rs.core.Application has an application path of /rest and my
BookResource has a path of /library, and for getting all books from the library, the sub-resource is books. I've tried every combination of the url below,
http://localhost:8080/john-[app|ear|ejb|web]/rest/library/books
all to no avail. every call results in a 404 error, and the only time i got ANYTHING is when i tried john-web combination, it threw some ugly exception in the browser. so the questions is with a rest service living inside an ejb module within an ear, what should the url be given the above information. nothing i've tried
seems to work!??
I've not included any code samples to try and keep the explanation short -- i didn't want to include every java file in my little project, but can add anything as requested.
Thanks,
JG
I am very much new to Kohana and Codeception world. I was exploring how to do testing in kohana using codeception.
I was able to run acceptance test. But now I want to create my Unit test for my demo app that has only sign and signup functionality.
How should I load the required files or the application instance which I will be using in the unit test.
Like I need to check if "Controller_Login" class exists. And then within this controller if "action_login" method exists or not.
I have gone through the Codeception documentation and it says that you need to auto-load your project in the unit/_bootstrap.php file.
So, how should I auto-load my project. Could you please guide me.
For unit test I have written this simple test
public function testMe()
{
$users = new User;
$this->assertInstanceOf('User', $users);
}
But when I run this it gives me error on console that "Class 'User' not found".
How should I auto-load my project please guide me.
Writing unit test for you app using Codecpetion you need to follow these points.
You need to load all your app in Codecpetion. So, that your test can easily access your classes.
There is one _bootstrap.php file at the root in test folder which Codecpetion creates once you bootstrap Codecpetion.
In this file you need to load your app.
For example I have done it like this to load my application folder.
define('APPPATH', realpath('application').'/');
So like this now you can create a unit test and access any class you would like to access.
I've just created my first test using AutoFixture. The SUT has the following constructor.
public LoggingService(
IClientDataProvider clientDataProvider, ... other dependencies...)
The test setup has the following code.
var fixture = new Fixture().Customize(new AutoMoqCustomization());
string ipAddress = "whatever";// fixture.CreateAnonymous<string>();
var clientDataProviderMock = fixture.Freeze<Mock<IClientDataProvider>>();
clientDataProviderMock.Setup(cdp => cdp.IpAddress).Returns(ipAddress);
LoggingService sut = fixture.CreateAnonymous<LoggingService>();
Now, when I examine the contents of sut, I see that the property IpAddress of the injected instance of IClientDataProvider returns null instead of "whatever".
What did I do wrong?
I copied the service and the necessary interfaces to an empty project and then the mocks worked as expected.
Interfaces that are types of constructor arguments of the service in the real project are defined in 3 separate assemblies that have further dependencies. I had several unexpected "Cannot load assembly" errors on the test start because several further assemblies were needed for those directly referenced assemblies. So it seems to be an assembly loading issue.
However, I tried a variation of the test with manual creation of the SUT instance with mock objects created manually using Moq and the test worked as expected
The solution was pretty surprising. When I was creating my unit test project I added the reference to Moq 4.0 first. AutoFixture was added later and since it seems to require Moq 3.1, I copied that dll directly to bin\Debug. However, the corresponding HintPath element in the project file still pointed to the 4.0 dll. As soon as I changed HintPath to point to the place where Moq 3.1 sits the test started to work properly. So Mark was right with his suggestion but the symptoms were quite different.
I'm using MVC 3 and using the following code when the application starts...
UnityContainer container = new UnityContainer();
new UnityMappings(container);
DependencyResolver.SetResolver(new UnityServiceLocator(container));
Now when the app runs I'm getting the following error (but only sometimes)...
Activation error occured while trying to get instance of type
IControllerFactory, key ""
Interestingly, if I continue with the web request, the website works normally.
Any ideas? I can't see what I'm doing differently from before when this worked fine.
Cheers, Ian.
MVC3 requests a lot more than just controllers from the DependencyResolver. For most of them MVC3 falls back to the default implementation in case the DependencyResolver does not return an instance.
In your case it requests the IControllerFactory which is unknown to your IoC container and it throws an exception which is caught by the UnityServiceLocator implementation and null is returned. MVC then falls back to the default controller factory.
Unlike other IoC containers Unity does not provide an optional TryResolve and therefore does not support a proper exceptionless implementation of the DependencyResolver.
I would suggest first looking through the config and make sure everything is correct there, then I would make sure I had all the assemblies needed for Unity referenced in the project. That error message may (in my experience) point to an error in config or a missing DLL, perhaps an assembly you want to load in the container or another DLL needed by a DLL loaded by Unity?
Hope this helps.