Domanda

Una domanda su come utilizzare Test-MVC per il test dell'unità.

Ho un semplice controller:

@Controller
@RequestMapping("/users")
public class UserController {        
    private UserService business;
    @Autowired
    public UserController(UserService bus)
    {
        business = bus;
    }
    @RequestMapping(value="{id}", method = RequestMethod.GET)
    public @ResponseBody User getUserById(@PathVariable String id) throws ItemNotFoundException{

        return business.GetUserById(id);

    }
.

(la mia idea è di mantenere i controller così sottili il più possibile.))

Per testare questo controller sto cercando di fare qualcosa del genere.

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:mvc-dispatcher-servlet.xml"})
public class UserControllerTest extends ControllerTestBase {

UserService mockedService;

@Before
public void Setup()
{

    MockitoAnnotations.initMocks( this );   
    mockedService = mock(UserService.class);

}

@Test
public void ReturnUserById() throws Exception{

    User user = new User();
    user.setName("Lasse");

    stub(mockedService.GetUserById("lasse")).toReturn(user);

    MockMvcBuilders.standaloneSetup(new UserController(mockedService)).build()
    .perform(get("/users/lasse"))
    .andExpect(status().isOk())
    .andExpect(?????????????????????????????);

}
.

La mia intenzione è quella di verificare che il corretto codice JSON sia restituito ,,,,,,

Io non sono un professionista ,, quindi non ho trovato un modo per sostituirlo ??????????????????????Con il codice per verificare la stringa restituita ma sono certo che ci deve essere un modo elegante per farlo

Qualcuno può riempirmi?

// LG

È stato utile?

Soluzione

content().string(containsString("some part of the string"))
.

Supponendo che tu abbia questa importazione:

import static org.springframework.test.web.server.result.MockMvcResultMatchers.*;
.

Aggiornamento: aggiungere JSONPATH anche in base ai tuoi commenti:

È possibile aggiungere una dipendenza da json-path , la 1,0.m1 sembraPer dipendere da una versione molto annata del percorso JSON però:

    <dependency>
        <groupId>com.jayway.jsonpath</groupId>
        <artifactId>json-path</artifactId>
        <version>0.5.5</version>
        <scope>test</scope>
    </dependency>   
.

Con questo il tuo test può assomigliare a questo:

.andExpect(jsonPath("$.persons[0].first").value("firstName"));
.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top