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.
Also note that we can wire other spring beans in our jUnit test classes using @Autowired annotation.
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.
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.
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 .
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With