2

I have a very simple unit test:

@RunWith(MockitoJUnitRunner.class)
public class RestControllerTest {

    protected MockMvc mockMvc;

    @Autowired
    WebApplicationContext wac;

    @InjectMocks
    protected RestController restController;

    @Mock
    protected UserService mockUserService;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);


        }
    }

I am stuck at figuring out how to Autowire WebApplicationContext in the above test. Please can somebody guide me how to do this.

P.S. I am using MockitoJUnitRunner I am not sure if this makes a difference or no. But I am new to Spring and Mockito so dont know much about either technologies.

Nick Div
  • 5,338
  • 12
  • 65
  • 127
  • This looks like duplicate of post http://stackoverflow.com/questions/2457239/injecting-mockito-mocks-into-a-spring-bean, and http://stackoverflow.com/questions/19808326/how-to-inject-a-mock-in-a-spring-context – Amit Mahajan Jul 11 '16 at 21:34
  • @amitmah :-) Thanks a lot. I'll go through the answer that you posted.. Appreciate the help. – Nick Div Jul 11 '16 at 21:45
  • @amitmah That answer is for how to get Mock objects working. My Mock objects are already working fine. I am having trouble getting the WebApplicationContext auto-wiring. – Nick Div Jul 11 '16 at 21:54

1 Answers1

5

You need to use Spring's JUnit runner in order to be able to @Autowire anything.

@RunWith(SpringJUnit4ClassRunner.class)

Then, you don't need to use @RunWith(MockitoJUnitRunner.class) because you're already calling MockitoAnnotations.initMocks(this);. You basically pick one or the other - It's shorter to use their runner, but when you can't use their runner (like in this situation), you call initMocks() in a @Before method.

Ultimately it depends on the Spring technologies you're using to decide what final steps you need to take. If you're using Spring Boot, here are their docs that show you the last bits you need to get a test up and running.

nickb
  • 59,313
  • 13
  • 108
  • 143
  • No I am not using Spring Boot. And I have tried using Spring Runner but somehow it keeps failing with following error : "Failed to load Application Context" now even though I added the full path of the context it is still not able to recognize the file and says "File not Found" its so weird but then I decided to use Mockito which was working fine with Spring version 4.2.6 where i did not have to AutoWire anything. But as soon as I downgraded to Spring 4.1.9 it fails. – Nick Div Jul 12 '16 at 03:04