Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you use spring's injection for unit testing a controller?

I want to test my spring mvc controller.

The controller has a service:

@Autowired
UserService userService

And my user service depends on (autowired) my UserDao and some other services like mongoDb etc.

Now I want the business logic to be tested in my UserService, but ofcourse I want to mock the responses from my UserDao and Mongodb etc.

How do I setup my unit test correctly?

Can I re-use the spring container's xml file that has all my beans etc. or do I create a new one? (I'm assuming I have to get the spring container involved here)

Looking for some guidance on this, any tutorials would be greatly appreciated.

Update

What I find strange is that for my spring controller (that doesn't implement from Controller) I was able to access my private varialbe to manually set my service, i.e:

@Controller
public class UserController {

   @Autowired
   UserService userService;
}

And in my unit test I could do:

UserController controller = new UserController();
controller.userService = ....

But for my UserService, which has UserDao autowired, I can't access the userDao property:

UserService userService = new UserServiceImpl();
userService.userDao = .... // not available

It makes sense since it is private, but how is it working for my controller?

like image 471
Blankman Avatar asked Jan 02 '12 15:01

Blankman


People also ask

What technique is used to unit test on a controller class?

We can write an unit test for this controller method by following these steps: Create the test data which is returned when the findAll() method of the TodoService interface is called. We create the test data by using a test data builder class.

Which annotation we can use to inject the service into rest controller?

Spring RestController annotation is used to create RESTful web services using Spring MVC.


1 Answers

Spring framework has very interesting features for testing. You can take a look at Spring reference guide. It can provide DI even in your JUnit test class.

@RunWith(SpringJUnit4ClassRunner.class)
// ApplicationContext will be loaded from "/applicationContext.xml" and "/applicationContext-test.xml"
// in the root of the classpath
@ContextConfiguration(locations={"/applicationContext.xml", "/applicationContext-test.xml"})
public class MyTest {
    // class body...
}

Briefly, you can use your own applicationContext.xml or even define a new one just for testing. I personally use a different one since I define another dataSource dedicated for testing purposes.

like image 73
Trein Avatar answered Sep 27 '22 19:09

Trein