java - 从测试用例调用 Controller 时,使用自动连线组件测试 Controller

我有一个 Controller

@RestController
public class Create {

    @Autowired
    private ComponentThatDoesSomething something;

    @RequestMapping("/greeting")
    public String call() {
        something.updateCounter();
        return "Hello World " + something.getCounter();
    }

}

我有那个 Controller 的组件

@Component
public class ComponentThatDoesSomething {
    private int counter = 0;

    public void updateCounter () {
        counter++;
    }

    public int getCounter() {
        return counter;
    }
}

我还对我的 Controller 进行了测试。

@RunWith(SpringRunner.class)
@SpringBootTest
public class ForumsApplicationTests {

    @Test
    public void contextLoads() {
        Create subject = new Create();
        subject.call();
        subject.call();
        assertEquals(subject.call(), "Hello World 2");
    }

}

当 Controller 调用 something.updateCounter() 时测试失败。我得到一个 NullPointerException。虽然我知道可以将 @Autowired 添加到构造函数中,但我想知道是否可以使用 @Autowired 字段来执行此操作。如何确保 @Autowired 字段注释在我的测试中有效?

最佳答案

Spring 不会自动连接您的组件,因为您使用 new 而不是 Spring 实例化您的 Controller ,因此组件未实例化

SpringMockMvc 测试检查它是否正确:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class CreateTest {
    @Autowired
    private WebApplicationContext context;

    private MockMvc mvc;

    @Before
    public void setup() {
        mvc = MockMvcBuilders
                .webAppContextSetup(context)
                .build();
    }

    @Test
    public void testCall() throws Exception {
        //increment first time
        this.mvc.perform(get("/greeting"))
                .andExpect(status().isOk());
        //increment secont time and get response to check
        String contentAsString = this.mvc.perform(get("/greeting"))
                .andExpect(status().isOk()).andReturn()
                .getResponse().getContentAsString();
        assertEquals("Hello World 2", contentAsString);
    }
}

关于java - 从测试用例调用 Controller 时,使用自动连线组件测试 Controller 为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39892534/

相关文章:

python - Flask 应用程序搜索栏

android-instrumentation - AndroidJUnitRunner + Act

curl - 如何使用 curl 访问 IBM speech-to-text api?

amazon-s3 - Haproxy - 将请求转发到 S3 托管站点

php - 使用带有表前缀的 DB::raw()

sql-server - 为什么即使回滚事务,SQL Server 仍保持可变状态?

Groovy - 无法在注释中使用静态最终字符串

c - FreeRTOS 中的抢占

angular - typescript 错误 TS1005 : '=' expected

python - 如何删除 Tkinter OptionMenu 小部件的边框