Lesson 9 of 15

Bogus and Class Methods

Duration: 2:05 Watch on YouTube (external link, opens in new tab)

Markdown version

Learn how to fake (external link, opens in new tab) class methods (statics) with Bogus.

In this lesson

Roy Osherove shows how Bogus fakes (external link, opens in new tab) class methods, which are almost like static methods in other languages, by using fake class on a shared logger and asserting that it should have received write. He adds that the testing tool can give hints about the design but should not dictate it.

Transcript

294 words

[00:02] (external link, opens in new tab) Okay. So what I want to explain now is what happens when you have methods that are class methods instead of instance methods. So in this case what we have if we go to a shared logger we have a method called self.write. Now if we want to fake (external link, opens in new tab) that method we can't just fake it on an instance because it's almost like a static method in other languages. So in this case we will use Bogus' abilities to fake class whole classes

[00:33] (external link, opens in new tab) By using fake class here. So you can just use the fake class construct by saying fake class shared logger and then to assert that a method on the shared a self method or a class method was called we can just say shared logger should have received write with the standard syntax. So instead of using the fake instance we just call the static method or the shared method which should and it should just work

[01:07] (external link, opens in new tab) Questions. That's one of the nice things that I like about dynamic languages is that they allow you to very very easily take over things which in other languages you would have a lot of problems. Now some people might say might you want that you might not not want to have class methods in the first place but I think that this is more of a design thing.

[01:37] (external link, opens in new tab) What we're what I'm trying to teach here is how to have good test specs and that shouldn't interfere with good design practices. You shouldn't let the the testing tool dictate exactly how your design looks. You can let it give you hints, but it's ultimately your choice how the design should look. So that's basically how you would work with the class methods. Okay.