opike
opike

Reputation: 7585

Using Junit with spring

I'm trying to set up a junit with spring and I'm trying to use spring's dependency injection to populate the test class. I'm wondering if this is something I should even be attempting? I think what I'm seeing is spring is instantiating the test class and performing the DI but then JUnit is creating it's own instance that hasn't had DI performed and the test is failing. I'm using JUnit 4.x and spring 3.1.1.

Upvotes: 2

Views: 773

Answers (2)

NimChimpsky
NimChimpsky

Reputation: 47300

You can use spring to inject dependencies into your tests, thus making it an integration test. Annotate like this

@RunWith(SpringJUnit4ClassRunner.class)
@Transactional
@ContextConfiguration(locations = "/applicationContext-TEST.xml")
public class MyTest {}

But it can be preferable to just test your spring managed classes as pojo's and use mock objects where appropriate.

For example a lot of controller methods have a Model injected at runtime by Spring. However to unit test them I just pass in an HashMap instance. And my service layer classes I can pass in a mocked dao, which is easy because I designed to an interface and use setter injection...

Upvotes: 7

aces.
aces.

Reputation: 4122

With jUnit, each test should be isolated with no dependency outside of test coverage. There are several test frameworks available that provide mock bean instantiation in Spring.

There is an excellent Martin Fowler article on Stubs and Mocks to begin with.

Mockito in combination with PowerMock, can help you test spring components, services and controllers.

Mockito Intro: https://code.google.com/p/mockito/
PowerMock Intro: http://code.google.com/p/powermock/

I understand this will take up time to research, learn and implement, but this is very beneficial for writing jUnit tests with Dependency Injected beans.

Upvotes: 1

Related Questions