当前位置: 动力学知识库 > 问答 > 编程问答 >

spring - Jhipster: run junittest without webserver

问题描述:

This is a question about testing.

I want to test my service and need the injections to work but I don't need a webservice starting up.

This is my code :

@RunWith(SpringJUnit4ClassRunner.class)

@SpringApplicationConfiguration(classes = MyWebApp.class)

@WebAppConfiguration

@Transactional

public class MyUserServiceTest {

@Inject

private MyUserService myUserService;

@Test

public void testRegister(){

myUserService.registerNew();

}

}

when I run it like this:

@RunWith(SpringJUnit4ClassRunner.class)

public class MyUserServiceTest {

I get this error:

Cannot load an ApplicationContext with a NULL 'contextLoader'

like this:

@RunWith(SpringJUnit4ClassRunner.class)

@SpringApplicationConfiguration(classes = MyWebApp.class)

public class MyUserServiceTest {

I get:

java.lang.IllegalStateException: Failed to load ApplicationContext

when I add the @WebAppConfiguation the test works but I get the webapplication running which takes a lot of time.

i now use my MyWebAppTest.class which is like this:

@ComponentScan

@EnableAutoConfiguration(exclude = { MetricFilterAutoConfiguration.class, MetricRepositoryAutoConfiguration.class })

@EnableConfigurationProperties({ JHipsterProperties.class, LiquibaseProperties.class })

public class MyWebAppTest { }

but stil the webservice is started....

网友答案:

In src/test/java, you could define a MyTestContext class that would exclude some configurations but define a spring application context with enough dependencies to make your test pass.

@SpringApplicationConfiguration(classes = MyTestContext.class)

You can start by defining it similarly to MyWebApp, make your test pass and then exclude some configurations until you reach the minimal set of dependencies, if your MyTestContext class is very specific to your service test you could also define as a static inner class of your test, this is a common pattern in Spring tests.

分享给朋友:
您可能感兴趣的文章:
随机阅读: