简体   繁体   中英

Initializing object using Mockito

I am having some difficulties in initializing object using Mockito for unit testing

This is my test code

@RunWith(SpringJUnit4ClassRunner.class)
class AreaControllerTest {

  @Mock
  CalculateArea calculateArea;

  @InjectMocks
  AreaController areaController;

  MockMvc mockMvc;

  @Before
  public void init()
  {

    mockMvc = standaloneSetup(areaController).build();
  }
  @Test
  void calculateArea() throws Exception{

    Mockito
        .when(calculateArea.calculateArea(Type.RECTANGLE, 5.0d, 4.0d))
        .thenReturn(20d);
    mockMvc.perform(
        MockMvcRequestBuilders.get("/api/area?type=RECTANGLE&param1=5&param2=4")
    )
    .andExpect(status().isOk())
    .andExpect(content().string("20.0"));

  }
}

The code to test

@Component
public class CalculateArea {

    @Autowired
    SquareService squareService;

    @Autowired
    RectangleService rectangleService;

    @Autowired
    CircleService circleService;

    public Double calculateArea(Type type, Double... r )
    {
        switch (type)
        {
            case RECTANGLE:
              if (r.length >= 2) {
                return rectangleService.area(r[0], r[1]);
              } else {
                throw new RuntimeException("Missing required params");
              }
            case SQUARE:
              if (r.length >= 1) {
                return squareService.area(r[0]);
              } else {
                throw new RuntimeException("Missing required param");
              }

            case CIRCLE:
              if (r.length >= 1) {
                return circleService.area(r[0]);
              } else {
                throw new RuntimeException("Missing required param");
              }
            default:
                throw new RuntimeException("Operation not supported");
        }
    }
}

RectangleService, CircleService and SquareService are annotated with org.springframework.stereotype.Service annotation I have tried many options and finally concluded to this. I am not getting where am I getting it wrong. I tried searching many places on the internet but couldn't find any help.

I believe you need to change your runner. Given your use of the SpringJUnit4ClassRunner, it looks like you're using JUnit 4. You should be able to simply replace

@RunWith(SpringJUnit4ClassRunner.class)

with

@RunWith(MockitoJUnitRunner.class)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM