简体   繁体   中英

UnitTests and Spring - create new beans?

I have an application where I use Spring (annotations, not xml), and I need to load the beans in my unit tests. I have the AppConfig class from my code which I want to use, but with a different datasource (one I define in the test folder). This is because I want to use an in memory DB in my tests, and not the real DB.

Here's how I try to run the AppConfig class:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {App.class, AppConfig.class})
public class DAOManagerTest {
   //All code goes here

  @AutoWired
  UserDAO userDAO; 

  @Test
  public void testGet() {
    List<User> test = userDAO.selectAll();
    for (User u: test) {
        u.toString();
    }
  }
}

This doesn't entirely work, as it fails on creating a bean inside the UserDAO class. I guess I need some tutorial / guide on how to deal with spring in unit tests. Should I define new beans in my test folder, or is it possible to user the spring class from my code? Also, is it possible to define a seperate datasource for the tests?

Yes. For example, if you define some beans in DAOManagerTest , using @Primary if necessary, and add DAOManagerTest.class to @ContextConfiguration .

There are so many other ways of arranging it though, like using profiles or mocks, etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM