【问题标题】:Is there a way to AutoWire WebApplicationContext in a test run by Mockito有没有办法在 Mockito 运行的测试中使用 AutoWire WebApplicationContext
【发布时间】:2016-07-11 21:30:05
【问题描述】:

我有一个非常简单的单元测试:

@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);


        }
    }

在上述测试中,我一直在弄清楚如何自动装配 WebApplicationContext。 请有人指导我如何做到这一点。

附:我正在使用 MockitoJUnitRunner 我不确定这是否会有所作为。但我是 Spring 和 Mockito 的新手,所以对这两种技术都不太了解。

【问题讨论】:

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


【解决方案1】:

您需要使用Spring's JUnit runner 才能@Autowire 任何东西。

@RunWith(SpringJUnit4ClassRunner.class)

那么,您不需要使用@RunWith(MockitoJUnitRunner.class),因为您已经在调用MockitoAnnotations.initMocks(this);。你基本上选择一个或另一个 - 使用他们的跑步者更短,但是当你不能使用他们的跑步者时(就像在这种情况下),你在 @Before 方法中调用 initMocks()

最终,这取决于您使用的 Spring 技术来决定您需要采取哪些最终步骤。如果您使用的是 Spring Boot,here 是他们的文档,向您展示了启动和运行测试所需的最后一点。

【讨论】:

  • 不,我没有使用 Spring Boot。我曾尝试使用 Spring Runner,但不知何故它一直失败并出现以下错误:“无法加载应用程序上下文”即使我添加了上下文的完整路径,它仍然无法识别文件并显示“找不到文件”它太奇怪了,但后来我决定使用 Mockito,它在 Spring 版本 4.2.6 上运行良好,我不需要 AutoWire 任何东西。但是一旦我降级到 Spring 4.1.9,它就失败了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-23
相关资源
最近更新 更多