Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make a test in xUnit with Assert.Contains

Tags:

c#

xunit

I try to make a test with xUnit finding the Id in a query in the controller.

My code its.

 public class CuestionarioTest
{
public readonly CuestionarioController _controller;
private readonly Mock<ICuestionarioServicio> _cuestionariosServicio;
private readonly Mock<IRespuestaServicio> _respuestaServicio;

public CuestionarioTest()
{
    _cuestionariosServicio = new Mock<ICuestionarioServicio>();
    _respuestaServicio = new Mock<IRespuestaServicio>();
    _controller = new  CuestionarioController(_cuestionariosServicio.Object, _respuestaServicio.Object);
}    
[Fact]
public async Task ComprobarBusquedaPorId()
{
    int id = 1;
    var result = await _controller.BuscarPorId(id);
    //Assert.IsType<OkObjectResult>(result);
    Assert.Contains(1, result.);    
}

}

This is my method

public class CuestionarioController : Controller
{
    private readonly ICuestionarioServicio _cuestionariosServicio;
    private readonly IRespuestaServicio _respuestaServicio;

    public CuestionarioController(ICuestionarioServicio cuestionarioServicio, IRespuestaServicio respuestaServicio)
    {
        _cuestionariosServicio = cuestionarioServicio;
        _respuestaServicio = respuestaServicio;
    }
    public async Task<IActionResult> BuscarPorId(int id)
    {
        return Ok(await _cuestionariosServicio.ObtenerPorId(id));
    }

I don't know how can validate if the result contain the Id with the result.

Please help.

like image 880
Rammon212 Avatar asked Sep 14 '25 05:09

Rammon212


1 Answers

If you cast the result, you can pull out the value:

var value = (result as OkObjectResult).Value;
Assert.Contains(1, value);
like image 126
Evan Trimboli Avatar answered Sep 15 '25 20:09

Evan Trimboli