Java Spring MVC + JUNIT + Not able to create a beans

By : Johnny
Source: Stackoverflow.com
Question!

I am struggling with my spring MVC web app. The app itself looks to work correctly. 2 days back i wanted to make some JUnit tests for my classes and i've read sth how to make it with Spring.

So i created my Test Class and i used below annotation to run tests with Spring and to load a proper contexts.

@RunWith(SpringJUnit4ClassRunner.class)
@ActiveProfiles(profiles = "test")
@ContextConfiguration(locations = {"classpath:/dispatcher-servlet.xml","classpath:/beans.xml","classpath:/jpaContext.xml"}

and when i try to run this test through maven or just by eclipse, im getting following error:

java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'messageSource' defined in class path resource [dispatcher-servlet.xml]: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration': Injection of autowired dependencies failed; nested exception is java.lang.NoClassDefFoundError: javax/servlet/ServletContext

Can anyone tell me why it happens ? App works correctly without testing and all beans are loaded without any issue.

WHy i have such a problem with tests?

Thanks in advance ! Jan

By : Johnny


Answers

You should add servlet-api as a dependency.

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.0.1</version>
    <scope>provided</scope>
</dependency>

Check this answer for more information.



You can implement parent class Machine with common logic and children classes with personal logic.

rails g model machine type:string customer_id:integer
mkdir app/models/machines
touch app/models/machines/bmw.rb
touch app/models/machines/renault.rb
...

app/models/machine.rb

class Machine < ActiveRecord::Base
  belongs_to :customer
  ...
  def country
    raise NotImplementedError
  end
end

app/models/machines/bmw.rb

class Bmw < Machine
  ...
  def country
    :germany
  end
end

app/models/machines/opel.rb

class Renault < Machine
  ...
  def country
    :france
  end
end

For example:

  • First bmw Bmw.first
  • First any car Machine.first
  • Get customer first Renault Renault.first.customer
  • Country any car Machine.all.sample.country, this method will call from any the child class.


In vanilla javascript:

document.getElementById('elementId').getAttribute('d');

With jquery use .attr():

$('#elementId').attr('d');


This video can help you solving your question :)
By: admin