lipanski / mockito

HTTP mocking for Rust!
MIT License
695 stars 59 forks source link

Getting 501 when testing with Actix #173

Closed finlaydotb closed 1 year ago

finlaydotb commented 1 year ago

So I am not 100% if I am the one not using the library right. But here is my set up

async fn mockito_server() -> Result<ServerGuard> {
    let server = mockito::Server::new();
    Ok(server)
}

fn mock_endpoint_a(mut server: &mut ServerGuard) -> Result<Mock> {
    let mock = server.mock("GET", "/a")
        .with_status(200)
        .with_header("content-type", "text/plain")
        .with_body("hello world")
        .create();

    Ok(mock)
}

Now in a test if I do this


    #[actix_web::test]
    async fn test_with_mocks() {

            let mut mockito_server = mockito_server().await.unwrap();
            let _m = mock_endpoint_a(&mut mockito_server).unwrap();

            let client = Client::new();

            let url = format!("{}/a", mocked_server.url());

            let res = client
                .get(&jurl)
                .send()
                .await.unwrap()
                .json()
                .await.unwrap();

            dbg!(res);
    }

I do get the mocked result. But now when I run the actix web app, which calls the mocked endpoint, I get back a 501 instead. That is this does not work

    #[actix_web::test]
    async fn test_with_mocks() {

        let mut mockito_server = mockito_server().await.unwrap();
        let _m = mock_endpoint_a(&mut mockito_server).unwrap();

        let app = test::init_service(App::new().route("/", web::get().to(index))).await;
        let req = test::TestRequest::default()
            .insert_header(ContentType::plaintext())
            .to_request();
        // internally this calls the mocked endpoint, but then it returns a 501.
        let resp = test::call_service(&app, req).await;
        assert!(resp.status().is_success());

    }

Any ideas what I may be doing wrong?

lipanski commented 1 year ago

I'm a bit confused about what you are testing here. I feel like I'd need some more context. are you trying to mock your actix web implementation or some external HTTP call triggered by your actix web implementation?

            let url = format!("{}/a", mocked_server.url());

            let res = client
                .get(&jurl)

what's jurl in here?

        let app = test::init_service(App::new().route("/", web::get().to(index))).await;

so you're calling / here, not /a => I assume /a points to an external HTTP call inside your actix web implementation then?


probably not the cause of your problem, but if you intend to write this for async, you should use the async methods everywhere, as explained here. There's also an example at the end of the Getting Started section.