Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring JUnit Test

Tags:

java

junit

spring

I like to test my spring code:

@ContextConfiguration(locations = { "/applicationContext.xml" })
@Transactional()
public class Test {

    @Autowired
    MyDao dao;

    @org.junit.Test
    @Rollback(false)
    public void testSomething() throws Exception {
        MyEntity e = new MyEntity();
        dao.create(e);
    }
}

Running this test with eclipse (as an JUNIT test) just gives an Nullpointer-Exception.

What have I done wrong? Thx!

like image 308
Udo R. Avatar asked Mar 27 '26 00:03

Udo R.


2 Answers

Just add @RunWith(SpringJUnit4ClassRunner.class) to your class:

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

    @Autowired
    MyDao dao;

    @org.junit.Test
    @Rollback(false)
    public void testSomething() throws Exception {
        MyEntity e = new MyEntity();
        dao.create(e);
    }
}

You need spring-test for that.

like image 67
t777 Avatar answered Mar 29 '26 13:03

t777


You can add a Transactional test base class like this

@ContextConfiguration(locations = "classpath*:applicationContext.xml")
public class IntegrateTestBase extends AbstractTransactionalJUnit4SpringContextTests {
}

Then wirite your test class

public class Test extends IntegrateTestBase {

    @Autowired
    MyDao dao;

    @org.junit.Test
    @Rollback(false)
    public void testSomething() throws Exception {
        MyEntity e = new MyEntity();
        dao.create(e);
    }
}

You need not write @ContextConfiguration and @Transcational in each test class

like image 31
Larry.Z Avatar answered Mar 29 '26 12:03

Larry.Z



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!