0

My Spring Boot app has a Controller that uses a Service that uses a bean I created (SharkMaster) that uses some values from a properties file.

When I'm running the app in regular mode it works OK.

However, when trying to run a unit test for the controller class, and providing it with a mock service it tries to create the real SharkMaster bean and fails since it can't find the values from the configuration.

I saw several posts and read some blog posts about similar issues, but at the current stage, the app is crashing in NullPointer when trying to run in unit test mode.

@Configuration
public class SharkMaster{

@Value("${sharkName}")
private String sharkName;

public SharkMaster(){
  // sharkName is null here and the NullPointer is thrown
}

The Controller test class:

@RunWith(SpringRunner.class)
@WebMvcTest(SharkController.class)
@ContextConfiguration(classes = {SharkMaster.class})
@TestPropertySource("classpath:application-test.yml")
public class SharkControllerTest {

@Autowired
private MockMvc mockMvc;

@MockBean
private SharkService sharkService;

I tried to add @PropertySource("classpath:application-test.yml") to the Controller test class but it didn't help.

I believe this question is not the same as this one , because the situation here in during the unit tests phase.

riorio
  • 6,500
  • 7
  • 47
  • 100
  • plz refer this [Answer](https://stackoverflow.com/questions/48329375/spring-boot-integration-test-business-layer/48335181#48335181) – rdj7 May 29 '18 at 09:00

1 Answers1

1

Remove your @ContextConfiguration and Try like this.

@RunWith(SpringRunner.class)
@WebMvcTest(controllers = SharkController.class)
public class SharkControllerTest {

@Autowired
private MockMvc mockMvc;

@InjectMocks
private SharkService sharkService;

@Mock
private SharkMaster sharkMaster;

.......
}
pvpkiran
  • 25,582
  • 8
  • 87
  • 134