What is the advantages of using ResourceConfig over Application(since ResourceConfig extends Application).
using ResourceConfig
#ApplicationPath("/")
public class MyApplication extends ResourceConfig {
public MyApplication() {
super(MultiPartResource.class, MultiPartResource.class, MultiPartFeature.class);
}
}
using Application
public class MyApplication extends Application {
#Override
public Set<Class<?>> getClasses() {
final Set<Class<?>> classes = new HashSet<Class<?>>();
// register resources and features
classes.add(MultiPartFeature.class);
classes.add(MultiPartResource.class);
classes.add(LoggingFilter.class);
return classes;
}
}
In the post Jersey 2 injection source for multipart formdata #Arul Dhesiaseelan answered to add the MultiPartFeature to both to enable that feature on the server side.
Could someone explain.
from the documentation: https://jersey.java.net/documentation/latest/deployment.html
"Compared to Application, the ResourceConfig provides advanced capabilities to simplify registration of JAX-RS components, such as scanning for root resource and provider classes in a provided classpath or a in a set of package names etc. All JAX-RS component classes that are either manually registered or found during scanning are automatically added to the set of classes that are returned by getClasses. "
Related
I currently have a ServiceBus Trigger in .Net Core 6.0 Isolated. Trying to figure out how to Use Dependency Injection, to set up the Trigger. Trying to figure out how to do this with .Net Core 6.0 Isolated.
I have a strongly typed model that is Bound to the appsettings.json file in the Program.cs code. That part works and has been verified. However when trying to do this with .Net Core 6 Isolated It give error about missing reference.
Here's my Config model that is bound to the appsettings.json file. I have left out the appsettings.json file for simplification
public class MyConfig
{
public string Topic { get; set; }
public string SubscriptionName { get; set; }
}
Here is the Service bus trigger class
public class ServiceBusTriggerClass
{
private readonly MyConfig _myConfig;
public ServiceBusTriggerClass(IOptions<MyConfig> config)
{
_myConfig= config.Value;
}
[Function("MySBFunction")]
public async Task MySBFunction([ServiceBusTrigger(_myConfig.Topic, _myConfig.SubscriptionName)] object myObject)
{
// Do things with the myObject thing.
}}
As of 1-13-2022 it is not possible to do this Using .Net 6 Isolated function. The function does not have access to the Host at this point.
I'm using ASP.NET Core 3.1 and XUnit for my unit tests.
I built a database context factory class that instantiates an in-memory version of my database:
public static class DbContextFactory
{
public static ApplicationDbContext CreateDbContext()
{
var options = new DbContextOptionsBuilder<ApplicationDbContext>()
.UseInMemoryDatabase(Guid.NewGuid().ToString())
.Options;
var modelBuilder = new ModelBuilder(new ConventionSet());
var dbContext = new ApplicationDbContext(options);
var onModelCreatingMethod = dbContext.GetType().GetMethod("OnModelCreating",
BindingFlags.Instance | BindingFlags.NonPublic);
onModelCreatingMethod.Invoke(dbContext,
new object[] { modelBuilder });
return dbContext;
}
}
This is the current test class I'm trying to use:
public class AdminServiceTests
{
public ApplicationDbContext context { get; set; }
public IAdminService adminService { get; set; }
public AdminServiceTests()
{
this.context = DbContextFactory.CreateDbContext();
this.adminService = new AdminService(userManager, context);
}
[Fact]
public async Task DeleteUserShouldDeleteUser()
{
// What to do ???
}
}
In order for me to test my admin service, I need to provide a user manager. It should be linked with the database I currently have created.
How can I make that happen?
You're making a common mistake of testing the framework. All your test needs to do is ensure that AdminService.DeleteUser calls UserManager.DeleteAsync. Whether or not that spirals down into actually removing the user from the database is 1) not a concern of the service and 2) an implementation detail of both ASP.NET Core Identity and EF Core, both of which have their own extensive test suites to ensure that happens.
As such, you can just use a library like Moq to create a mock of UserManager<TUser> and then do something like:
userManagerMock.Verify(x => x.DeleteAsync(user), Times.Once());
It's worth mentioning here that this also serves to point out a bit of a flaw in this kind of design. You have a dependency on ASP.NET Core Identity whether or not you put an AdminService wrapper around that. Unless your service is doing something special outside of just proxying to UserManager here (e.g. coordinating multiple actions, like maybe deleting the user triggers a notification or something), then your service is pointless, and you should just use UserManager directly. Developers make this kind of mistake constantly; abstraction for the sake of abstraction only hurts your code. It adds additional maintenance concerns, testing concerns, and obscures what the code is actually doing.
Hello I am finding the solution for getting the bean instantiated given in #ContextConfiguration when we run the Vaadin test case with spring boot.
Here is some piece of the code which I have configured.
#WebAppConfiguration
#RunWith(JUnit4.class)
#ContextConfiguration(loader = AnnotationConfigContextLoader.class, classes = UIConfiguration.class)
public abstract class BaseTestCase extends TestBenchTestCase {
//code stuff
}
#Configuration
#PropertySource("classpath:META-INF/spring/application.properties")
#ComponentScan(basePackages = "com.ui", excludeFilters = #ComponentScan.Filter(value = Controller.class, type = FilterType.ANNOTATION))
#EnableAsync
#EnableI18N
public class UIConfiguration implements AsyncConfigurer {
//block of code
}
You should be able to use the ClassRule and Rule Spring provide if you do not want to use the SpringRunner
#ClassRule
public static final SpringClassRule SPRING_CLASS_RULE = new SpringClassRule();
#Rule
public final SpringMethodRule springMethodRule = new SpringMethodRule();
See the java doc for more details,
https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/test/context/junit4/rules/SpringClassRule.html
SpringClassRule is a custom JUnit TestRule that supports class-level features of the Spring TestContext Framework in standard JUnit tests by means of the TestContextManager and associated support classes and annotations.
In contrast to the SpringJUnit4ClassRunner, Spring's rule-based JUnit support has the advantage that it is independent of any Runner and can therefore be combined with existing alternative runners like JUnit's Parameterized or third-party runners such as the MockitoJUnitRunner.
In order to achieve the same functionality as the SpringJUnit4ClassRunner, however, a SpringClassRule must be combined with a SpringMethodRule, since SpringClassRule only supports the class-level features of the SpringJUnit4ClassRunner.
Hi I'm trying to test my Service and Dao layers for a Java EE 7 application.
So I looking for testing solutions follow tutorials using Arquillian with junit test and wildfly remote dependence.
Dao and Service interfaces with relative implementations have been created, following my junit test with Arquillian:
#RunWith(Arquillian.class)
public class GenericServiceTest {
#Inject
private EmployeeService employeeService;
#Deployment
public static JavaArchive createDeployment() {
return ShrinkWrap
.create(JavaArchive.class)
.addAsManifestResource("META-INF/persistence.xml",
"persistence.xml")
.addClasses(EmployeeDao.class, EmployeeDaoImpl.class,
EmployeeService.class, EmployeeServiceImpl.class,
Employee.class)
.addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml");
}
#Test
#Transactional
public void should_crud() {
// Gets all the objects
assertNotNull(employeeService);
Employee employee = employeeService.get(new Integer(1));
assertNotNull(employee);
}
}
Running class as JUnit Test it doesn't work with this error:
Caused by: java.lang.Exception: "WFLYCTL0216: Management resource '[(\"deployment\" => \"test.war\")]' not found"
Test pass if any classes has been added to ShrinkWrap as following:
#RunWith(Arquillian.class)
public class GenericDaoTest {
#Inject
private EmployeeService employeeService;
#Deployment
public static JavaArchive createTestableDeployment() {
final JavaArchive jar = ShrinkWrap.create(JavaArchive.class)
.addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml");
return jar;
}
#Test
public void should_crud() {
}
}
How can I create a working test using arquillian for Java EE 7 adding service class implementations?
And I have To add every Class and Intefaces that have to be called (for example all entities,dao etc classes) or only Service Interface and implementation Class?
Thanks a lot
Since you're developing a javaee application, I would suggest you to create a War archive instead of Jar.
You can add the whole package using
ShrinkWrap.addPackages(true, "com.yourpackage.name") so you don't have to add your classes independently.
If I understand the question correctly you want to test a war archive.
If this is the case you should change
return ShrinkWrap
.create(JavaArchive.class)
to
return ShrinkWrap
.create(WarArchive.class)
In addition you should add your persistence.xml file to the META-INF folder like:
.addAsResource("test-persistence.xml", "META-INF/persistence.xml")
If you want to use the annotation #Transactional in your tests, you need to add a few dependencies to your test scope. If you didn't add them yet you can read at http://arquillian.org/modules/transaction-extension/ what dependencies to add.
I have the following RouteBuilder Class and I am using dependency injection here. How can I test this route builder? I am using JUnit and camel test classes.
public class TestRoute extends RouteBuilder {
private ServiceConfiguration serviceConfiguration;
public TestRoute(ServiceConfiguration serviceConfiguration) {
this.serviceConfiguration = serviceConfiguration;
}
#Override
public void configure() throws Exception {
String incomingURI = serviceConfiguration.getQueueConfiguration().getURI();
String outgoingURI = serviceConfiguration.getHTTPConfiguration().getURI();
from(incomingURI).
setHeader(Exchange.HTTP_METHOD, constant("PUT")).setHeader(Exchange.CONTENT_TYPE, constant("application/json")).
to(outgoingURI);
}
}
My thoughts:
Creating a testConfiguration extending ServiceConfiguration and pass that. But for that I need to set all the configuration and all because the serviceConfiguration contains many other classes. Can I use Mockito here? What is the correct and easy way to test this?
EDIT: I was using the existing route, so that I don't have to write it again. Looks like that is not the correct way of testing in camel. See my test class. Of course, its not working.
public class RabbitMQRouteTest extends CamelTestSupport {
#Mock
ServiceConfiguration serviceConfiguration;
#Override
protected RouteBuilder createRouteBuilder() throws Exception {
System.out.println("testing");
return new TestRoute(serviceConfiguration);
}
#Test
public void testConfigure() throws Exception {
System.out.println("test");
when(serviceConfiguration.getName()).thenReturn("file://target/inbox");
template.sendBodyAndHeader("file://target/inbox", "Hello World",Exchange.FILE_NAME, "hello.txt");
Thread.sleep(1000);
File target = new File("target/outbox/hello.txt");
assertTrue("File not moved", target.exists());
}
}
As you use #Mock, MockitoAnnotations.initMocks has to be invoked. Additionally, when has also be called before passing the reference to TestRoute:
#Override
protected RouteBuilder createRouteBuilder() throws Exception {
// Initialize serviceConfiguration
MockitoAnnotations.initMocks(this);
when(serviceConfiguration.getName()).thenReturn("file://target/inbox");
return new TestRoute(serviceConfiguration);
}
Alternatively to #Mock and MockitoAnnotations.initMocks, just use:
serviceConfiguration = org.mockito.Mockito.mock(ServiceConfiguration.class);
As when is invoked in createRouteBuilder, serviceConfiguration.getName() always returns the same result for all test methods in the JUnit test class. This could be a problem, if different test methods need different URIs.
Alternatively, you may use adviceWith instead as described here.
Camel has two ways to do the route tests, CamelSpringTestSupport and CamelTestSupport.
CamelSpringTestSupport
You can set the route with some camel-whatever-test.xml to setup the route in Spring configuration xml.
CamelTestSupport
You can set the route with RouteBuilder createRoute. And configure the endpoint with mock components.
Here is some reference link, do not forget to add the dependency jars:
http://camel.apache.org/testing.html
Using mockito makes sense in your case as you only need some small parts of the ServiceConfiguration.
On the other hand it is a bad sign that you need it for setting configuration data. You should check if your configuration can be split up into separate parts or not be used in the RouteBuilder at all. If you have one configuration structure that is used in all parts of your code you create a tight coupling between things that should be separate. If you just need the two properties queue uri and http uri in your routebuilder then consider just having two setters for them.