Is there a way to AutoWire WebApplicationContext in a test run by Mockito

时间:2016-07-11 21:30:06

标签: java unit-testing spring-mvc junit mockito

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.

1 个答案:

答案 0 :(得分:4)

您需要使用Spring's JUnit runner才能''任何内容。

@Autowire

然后,您不需要使用@RunWith(SpringJUnit4ClassRunner.class) ,因为您已经在调用@RunWith(MockitoJUnitRunner.class)。你基本上选择其中一个 - 使用跑步者的时间较短,但是当你不能使用他们的跑步者时(比如在这种情况下),你可以在{{1}中拨打MockitoAnnotations.initMocks(this);方法。

最终,它取决于您使用的Spring技术来决定您需要采取的最终步骤。如果你正在使用Spring Boot,那么here就是他们的文档,可以向你展示测试运行所需的最后几位。

相关问题