0

Assume two @Component's are defined, like this:

@Component
public class UnderTesting {
}
@Component
public class Irrelevant {
}

The unit test is like this:

@SpringBootTest
public Test_UnderTesting {
    @Autowired
    private UnderTesting foo;

    @Test
    public void testSomething() {
    }
}

When running this test case with mvn test, spring will construct component Irrelevant even though it's completely irrelevant.

In my case the component Irrelevant cannot be constructed due to unavailability of complex dependencies in the unit test environment.

My question is: how to avoid constructing Irrelevant (and other unnecessary components) during unit test ?

I'm kind new to spring boot, so I may have been heading a wrong direction, any suggestions are welcome.

4 Answers 4

3

One thing to understand is, as soon as you use @SpringBootTest, it's not a unit test anymore. The point of using that annotation is, that your application context starts as similar as possible to the production use.

You could define a separate configuration class for this test case specifically, where you only create a bean of the class UnderTesting, like this:

@SpringBootTest(classes = {TestConfiguration.class})

where in TestConfiguration.class you could create a bean factory method like this:

public UnderTesting underTesting() {
    return new UnderTesting();
}

but i would rather look if you can write this test as a real unit test (if that's what you want), without using any Spring Boot functionality, and mock any dependencies.

Sign up to request clarification or add additional context in comments.

Comments

0

How about creating a test profile to use when you run your tests and annotate your Irrelevant class with @Profile("!test")?

2 Comments

This not gonna work, since Irrelevant has its own test cases.
Then the only option is I think passing a custom configuration to your test as @dunni wrote
0

The simplest way using mockito:

@SpringBootTest
public Test_UnderTesting {

    @MockBean
    private Irrelevant irrelevant; //Autowiring the unnecessary component as a mock

    @Autowired
    private UnderTesting foo;

    @Test
    public void testSomething() {
    }
}

Dependencies required:

Comments

-1

We can load the component lazily, i.e. by using @Lazy annotation on top of @Component

Please refer this link for more information: https://www.baeldung.com/spring-lazy-annotation

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.