Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assert that the controller has been created in Spring Boot?

According to the tutorial Testing the Web Layer, testing that the controller has been created can be done with the following code:

@Test
public void contexLoads() throws Exception {
    assertThat(controller).isNotNull();
}

but I get the following error:

The method assertThat(T, Matcher<? super T>) in the type Assert is not applicable for the arguments (HomeController)"

even with the statement:

import static org.junit.Assert.assertThat;

The code of my class is the same than the one given in the example:

package com.my_org.my_app;

import static org.assertj.core.api.Assertions.assertThat;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

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

    @Autowired
    private HomeController controller;

    @Test
    public void contexLoads() throws Exception {
        assertThat(controller).isNotNull();
    }
}

If I change the assert statement to:

@Test
public void contexLoads() throws Exception {
    assertNotNull(controller);
}

it works as expected.

My controller class has some Autowired objects, but since they are managed by Spring Boot it should not be an issue. Any idea of what could be wrong with assertThat(controller).isNotNull();? Thanks in advance.

like image 842
j.xavier.atero Avatar asked Dec 06 '25 05:12

j.xavier.atero


1 Answers

You used the wrong assertThat import. You should use the following:

import static org.assertj.core.api.Assertions.assertThat;

The correct method is located in AssertJ library, not in JUnit.

like image 154
OneHalf Avatar answered Dec 08 '25 20:12

OneHalf