Nic*_*Div 2 java junit unit-testing spring-mvc mockito
我有一个非常简单的单元测试:
@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);
}
}
Run Code Online (Sandbox Code Playgroud)
在上面的测试中,我一直在弄清楚如何自动装配 WebApplicationContext。请有人指导我如何做到这一点。
PS 我正在使用 MockitoJUnitRunner 我不确定这是否有所作为。但是我是 Spring 和 Mockito 的新手,所以对这两种技术都不太了解。
您需要使用Spring 的 JUnit 运行程序才能执行@Autowire任何操作。
@RunWith(SpringJUnit4ClassRunner.class)
Run Code Online (Sandbox Code Playgroud)
然后,您不需要使用,@RunWith(MockitoJUnitRunner.class)因为您已经在调用MockitoAnnotations.initMocks(this);. 你基本上选择一个或另一个 - 使用他们的跑步者更短,但是当你不能使用他们的跑步者时(就像在这种情况下),你调用initMocks()一个@Before方法。
最终,这取决于您使用的 Spring 技术来决定您需要采取哪些最终步骤。如果您使用的是 Spring Boot,这里是他们的文档,向您展示了启动和运行测试所需的最后一点。
| 归档时间: |
|
| 查看次数: |
1594 次 |
| 最近记录: |