Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

spring 3 autowiring and junit testing

My code:

@Component public class A {     @Autowired     private B b;      public void method() {} }  public interface X {...}  @Component public class B implements X {     ... } 

I want to test in isolation class A. Do I have to mock class B? If yes, how? Because it is autowired and there is no setter where i could send the mocked object.

like image 396
mike27 Avatar asked Sep 07 '10 17:09

mike27


People also ask

Can we use Autowired in JUnit?

Also note that we can wire other spring beans in our jUnit test classes using @Autowired annotation.

Can we use @autowired in test class?

To check the Service class, we need to have an instance of the Service class created and available as a @Bean so that we can @Autowire it in our test class. We can achieve this configuration using the @TestConfiguration annotation.

Which test is used at Autowired?

if you are writing unit tests a recommend you use @Mock and @InjectMocks . But if you really want test all the flow and need to inject classes, you can @RunWith(SpringJUnit4ClassRunner. class) and @Autowired your classes. Hello pedroso.

What annotation causes JUnit to let Spring boot control the test?

Spring Boot provides a @SpringBootTest annotation, which can be used as an alternative to the standard spring-test @ContextConfiguration annotation when you need Spring Boot features. The annotation works by creating the ApplicationContext used in your tests through SpringApplication .


1 Answers

I want to test in isolation class A.

You should absolutely mock B, rather than instantiate and inject an instance of B. The point is to test A whether or not B works, so you should not allow a potentially broken B interfere with the testing of A.

That said, I highly recommend Mockito. As mocking frameworks go, it is extremely easy to use. You would write something like the following:

@Test public void testA() {     A a = new A();     B b = Mockito.mock(B.class); // create a mock of B     Mockito.when(b.getMeaningOfLife()).thenReturn(42); // define mocked behavior of b     ReflectionTestUtils.setField(a, "b", b); // inject b into the B attribute of A      a.method();      // call whatever asserts you need here } 
like image 76
earldouglas Avatar answered Sep 20 '22 09:09

earldouglas