user86834
user86834

Reputation: 5645

Tests injecting beans with @Autowired annotations

I want to write unit test using Junit and Mockito, in this case I don't want to write integration tests. The method that I want to test uses variables that are injected via Spring using the @Value or @Autowired annotations. How can I populate the injected variables so that when I run a test they are not null. Before days of annotations I would have created mocked classes of the variables and set them via setter methods.

I'm writing unit tests so I would prefer not to use @RunWith(SpringJUnit4ClassRunner.class).

Upvotes: 0

Views: 2059

Answers (1)

kryger
kryger

Reputation: 13181

You can use the MockitoJUnitRunner.

class SystemUnderTest {
    @Autowired
    private Dependency dep;

    // ...
}
@RunWith(MockitoJUnitRunner.class)
public class YourTest {
    @Mock
    private Dependency mockDependency;

    @InjectMocks
    private SystemUnderTest testee;

    @Test
    public void testSystem() {
        // at this point testee is already injected with mockDependency
    }
}

Upvotes: 1

Related Questions