Humor has a long and proud tradition in speculative fiction. Gulliver’s Travels (1726) by satirist Jonathan Swift has many hilarious scenes, most memorably when Gulliver puts out a fire in Lilliput by “making water”.
I see humor appearing in three ways in speculative fiction. The first is straight out comic writing. For me the unrivaled modern master is the late Douglas Adams (Hitchhiker’s Guide). Adams, by the way, is an example of the interesting fact that being funny in print and funny in person do not always go together. I saw Adams live in concert in the 1980’s. He wasn’t especially funny. A counterexample is Woody Allen, who not only created the comic sci fi masterpiece Sleeper but also wrote some of the funniest stories in the English language (collected in books such as Without Feathers, Getting Even, and Side Effects).
The second is work that, while serious, is leavened with humor. Lois McMaster Bujold’s magnificent Vorkosigan series is a good example. Her books are crammed with brilliant epigrams. They contain much darkness – rape, murder, torture – stuff that I normally wouldn’t want to read about. Somehow she makes it all palatable by mixing in witticisms and impeccable comic timing.
Third, some speculative fiction is unintentionally funny. When I saw David Lynch’s incomprehensible film Dune in the theater in 1984, the audience burst out laughing in the scene where the guy rides the giant worm. So if you’re a writer of serious fiction, avoid situations where your hero straddles a gigantic penis-shaped creature. In fact, I’ll go out on a limb here and suggest avoiding all aliens that resemble human genitalia, unless you’re writing comedy. But hey, it worked for Frank Herbert.
Like any other skill, skill at writing humorous fiction is a combination of innate ability and deliberate practice. Part of practicing the craft is learning what works for readers, and what doesn’t. For any writer, this feedback is enormously helpful. For comic writers, this feedback comes in a particularly measurable form: laughter. If possible, read your work aloud to a small audience (or even better, have someone else read it aloud to them). You could use a writing group or just a few friends and family members. You may be surprised at which lines got big laughs, and which lines bombed.