Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use XCTests to test for print statements?

I am trying to test whether a function prints out something. How can I do this with XCTests? If this is possible, are there factual reasons to do it and not do it?

Thanks!

like image 437
Akash Kundu Avatar asked Dec 01 '18 07:12

Akash Kundu


People also ask

How do I test a swift closure?

Basically to test asynchronous operation/closure you must: create an expectation that is an instance of XCTestExpectation. execute your closure, make your assert on the closure return value/parameter and call the method fulfill of XCTestExpectation.

What to unit test ios?

A unit test is a function you write that tests something about your app. A good unit test is small. It tests just one thing in isolation. For example, if your app adds up the total amount of time your user spent doing something, you might write a test to check if this total is correct.

How to write UI tests ios?

Recording a UI Test From the debug bar, click the Record UI Test button. Xcode will launch the app and run it. You can interact with the element on-screen and perform a sequence of interactions for any UI test. Whenever you interact with an element, Xcode writes the corresponding code for it into your method.


2 Answers

@Mike Taverne is right. For giggles if you did want to actually test against a print statement you could extend the print function like so:

var printWasWrittenTo: Bool = false

public func print(_ items: Any..., separator: String = " ", terminator: String = "\n") {
    var output: String = items.map { "\($0)" }.joined(separator: separator)

    printWasWrittenTo = true //test against this variable being changed

    Swift.print(output, terminator: terminator)
}
like image 112
Alex Bailey Avatar answered Oct 21 '22 01:10

Alex Bailey


I don't know of a way to test a print statement, but I don't think it matters. The output of a print statement is irrelevant to what your app actually does. You should test what data your app changes, what it displays to the user, etc.

like image 29
Mike Taverne Avatar answered Oct 21 '22 02:10

Mike Taverne