Moq a Class and Still use its Methods
I am doing a Mock of a class, with Moq framework. However, I am not able to grab or call the Class's methods. How would I resolve this issue in the unit test below? Trying to compile program to extract the methods in Moq in class. Error is listed below.
Class:
using System;
using ElectronicsStore.Models;
using Microsoft.Extensions.Logging;
namespace ElectronicsStore.Service
{
public class ParseVendorSupply
{
private readonly ILogger _logger;
public ParseVendorSupply(ILogger logger)
{
_logger = logger;
}
public VendorSupply FromCsv(string csvLine)
{
VendorSupply vendorsupply = new VendorSupply();
try
{
string values = csvLine.Split(',');
if (values.Length > 3)
{
throw new System.ArgumentException("Too much data");
}
vendorsupply.VendorId = Convert.ToInt16(values[0]);
vendorsupply.ProductId = Convert.ToInt16(values[1]);
vendorsupply.Quantity = Convert.ToInt16(values[2]);
}
catch (Exception)
{
_logger.LogInformation("An exception was thrown attempting");
}
return vendorsupply;
}
}
}
public Startup(IConfiguration configuration, ILogger<Startup> logger)
{
Configuration = configuration;
_logger = logger;
}
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton(new LoggerFactory().AddConsole().AddDebug());
services.AddLogging();
NUnit Test:
public class ParseVendorSupplyNunit
{
[Test]
public void FromCsv_ParseCorrectly_Extradata()
{
var logger = new Mock<ILogger>();
Mock<ParseVendorSupply> parseVendorSupplytest = new Mock<ParseVendorSupply>(logger);
var test = new Mock<ParseVendorSupply>(logger);
string csvLineTest = "5,8,3,9,5";
parseVendorSupplytest.FromCsv
// Receive error: Mock<ParseVendorSupply>' does not contain a definition for 'FromCsv' and no accessible extension method 'FromCsv' accepting a first argument of type 'Mock<ParseVendorSupply>' could be found (are you missing a using directive or an assembly reference?)
}
c# asp.net-core nunit moq
add a comment |
I am doing a Mock of a class, with Moq framework. However, I am not able to grab or call the Class's methods. How would I resolve this issue in the unit test below? Trying to compile program to extract the methods in Moq in class. Error is listed below.
Class:
using System;
using ElectronicsStore.Models;
using Microsoft.Extensions.Logging;
namespace ElectronicsStore.Service
{
public class ParseVendorSupply
{
private readonly ILogger _logger;
public ParseVendorSupply(ILogger logger)
{
_logger = logger;
}
public VendorSupply FromCsv(string csvLine)
{
VendorSupply vendorsupply = new VendorSupply();
try
{
string values = csvLine.Split(',');
if (values.Length > 3)
{
throw new System.ArgumentException("Too much data");
}
vendorsupply.VendorId = Convert.ToInt16(values[0]);
vendorsupply.ProductId = Convert.ToInt16(values[1]);
vendorsupply.Quantity = Convert.ToInt16(values[2]);
}
catch (Exception)
{
_logger.LogInformation("An exception was thrown attempting");
}
return vendorsupply;
}
}
}
public Startup(IConfiguration configuration, ILogger<Startup> logger)
{
Configuration = configuration;
_logger = logger;
}
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton(new LoggerFactory().AddConsole().AddDebug());
services.AddLogging();
NUnit Test:
public class ParseVendorSupplyNunit
{
[Test]
public void FromCsv_ParseCorrectly_Extradata()
{
var logger = new Mock<ILogger>();
Mock<ParseVendorSupply> parseVendorSupplytest = new Mock<ParseVendorSupply>(logger);
var test = new Mock<ParseVendorSupply>(logger);
string csvLineTest = "5,8,3,9,5";
parseVendorSupplytest.FromCsv
// Receive error: Mock<ParseVendorSupply>' does not contain a definition for 'FromCsv' and no accessible extension method 'FromCsv' accepting a first argument of type 'Mock<ParseVendorSupply>' could be found (are you missing a using directive or an assembly reference?)
}
c# asp.net-core nunit moq
add a comment |
I am doing a Mock of a class, with Moq framework. However, I am not able to grab or call the Class's methods. How would I resolve this issue in the unit test below? Trying to compile program to extract the methods in Moq in class. Error is listed below.
Class:
using System;
using ElectronicsStore.Models;
using Microsoft.Extensions.Logging;
namespace ElectronicsStore.Service
{
public class ParseVendorSupply
{
private readonly ILogger _logger;
public ParseVendorSupply(ILogger logger)
{
_logger = logger;
}
public VendorSupply FromCsv(string csvLine)
{
VendorSupply vendorsupply = new VendorSupply();
try
{
string values = csvLine.Split(',');
if (values.Length > 3)
{
throw new System.ArgumentException("Too much data");
}
vendorsupply.VendorId = Convert.ToInt16(values[0]);
vendorsupply.ProductId = Convert.ToInt16(values[1]);
vendorsupply.Quantity = Convert.ToInt16(values[2]);
}
catch (Exception)
{
_logger.LogInformation("An exception was thrown attempting");
}
return vendorsupply;
}
}
}
public Startup(IConfiguration configuration, ILogger<Startup> logger)
{
Configuration = configuration;
_logger = logger;
}
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton(new LoggerFactory().AddConsole().AddDebug());
services.AddLogging();
NUnit Test:
public class ParseVendorSupplyNunit
{
[Test]
public void FromCsv_ParseCorrectly_Extradata()
{
var logger = new Mock<ILogger>();
Mock<ParseVendorSupply> parseVendorSupplytest = new Mock<ParseVendorSupply>(logger);
var test = new Mock<ParseVendorSupply>(logger);
string csvLineTest = "5,8,3,9,5";
parseVendorSupplytest.FromCsv
// Receive error: Mock<ParseVendorSupply>' does not contain a definition for 'FromCsv' and no accessible extension method 'FromCsv' accepting a first argument of type 'Mock<ParseVendorSupply>' could be found (are you missing a using directive or an assembly reference?)
}
c# asp.net-core nunit moq
I am doing a Mock of a class, with Moq framework. However, I am not able to grab or call the Class's methods. How would I resolve this issue in the unit test below? Trying to compile program to extract the methods in Moq in class. Error is listed below.
Class:
using System;
using ElectronicsStore.Models;
using Microsoft.Extensions.Logging;
namespace ElectronicsStore.Service
{
public class ParseVendorSupply
{
private readonly ILogger _logger;
public ParseVendorSupply(ILogger logger)
{
_logger = logger;
}
public VendorSupply FromCsv(string csvLine)
{
VendorSupply vendorsupply = new VendorSupply();
try
{
string values = csvLine.Split(',');
if (values.Length > 3)
{
throw new System.ArgumentException("Too much data");
}
vendorsupply.VendorId = Convert.ToInt16(values[0]);
vendorsupply.ProductId = Convert.ToInt16(values[1]);
vendorsupply.Quantity = Convert.ToInt16(values[2]);
}
catch (Exception)
{
_logger.LogInformation("An exception was thrown attempting");
}
return vendorsupply;
}
}
}
public Startup(IConfiguration configuration, ILogger<Startup> logger)
{
Configuration = configuration;
_logger = logger;
}
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton(new LoggerFactory().AddConsole().AddDebug());
services.AddLogging();
NUnit Test:
public class ParseVendorSupplyNunit
{
[Test]
public void FromCsv_ParseCorrectly_Extradata()
{
var logger = new Mock<ILogger>();
Mock<ParseVendorSupply> parseVendorSupplytest = new Mock<ParseVendorSupply>(logger);
var test = new Mock<ParseVendorSupply>(logger);
string csvLineTest = "5,8,3,9,5";
parseVendorSupplytest.FromCsv
// Receive error: Mock<ParseVendorSupply>' does not contain a definition for 'FromCsv' and no accessible extension method 'FromCsv' accepting a first argument of type 'Mock<ParseVendorSupply>' could be found (are you missing a using directive or an assembly reference?)
}
c# asp.net-core nunit moq
c# asp.net-core nunit moq
asked Nov 12 at 7:55
JoeThomas
677
677
add a comment |
add a comment |
1 Answer
1
active
oldest
votes
Moq exposes the mocked object through the .Object
property. So in your case, you could do:
parseVendorSupplytest.Object.FromCsv(csvLineTest);
That said. I'm not sure this is what you wanted to do in first place. Assuming you're trying to test ParseVendorSupply
using a mocked logger, I believe your code should look like:
[Test]
public void FromCsv_ParseCorrectly_Extradata()
{
var logger = new Mock<ILogger>();
var parseVendorSupply = new ParseVendorSupply(logger.Object);
string csvLineTest = "5,8,3,9,5";
var result = parseVendorSupplytest.FromCsv(csvLineTest);
// Add your assertions here
}
Also note that you can use the Mock.Of<T>()
shortcut to directly retrieve the mocked object if you don't need any setup:
var parseVendorSupply = new ParseVendorSupply(Mock.Of<ILogger>());
hmm, for some reason, before the logger and the mock framework, it was running with unit test pass, now receive Message: Expected: <System.ArgumentException> But was: no exception thrown", however when I debug exception was thrown
– JoeThomas
Nov 12 at 8:08
@JoeThomas You'll have to show a bit of code to explain :p The exception is caught in yourParseVendorSupply.FromCsv
method, so what does your assertion look like?
– Kevin Gosse
Nov 12 at 8:11
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53257882%2fmoq-a-class-and-still-use-its-methods%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
Moq exposes the mocked object through the .Object
property. So in your case, you could do:
parseVendorSupplytest.Object.FromCsv(csvLineTest);
That said. I'm not sure this is what you wanted to do in first place. Assuming you're trying to test ParseVendorSupply
using a mocked logger, I believe your code should look like:
[Test]
public void FromCsv_ParseCorrectly_Extradata()
{
var logger = new Mock<ILogger>();
var parseVendorSupply = new ParseVendorSupply(logger.Object);
string csvLineTest = "5,8,3,9,5";
var result = parseVendorSupplytest.FromCsv(csvLineTest);
// Add your assertions here
}
Also note that you can use the Mock.Of<T>()
shortcut to directly retrieve the mocked object if you don't need any setup:
var parseVendorSupply = new ParseVendorSupply(Mock.Of<ILogger>());
hmm, for some reason, before the logger and the mock framework, it was running with unit test pass, now receive Message: Expected: <System.ArgumentException> But was: no exception thrown", however when I debug exception was thrown
– JoeThomas
Nov 12 at 8:08
@JoeThomas You'll have to show a bit of code to explain :p The exception is caught in yourParseVendorSupply.FromCsv
method, so what does your assertion look like?
– Kevin Gosse
Nov 12 at 8:11
add a comment |
Moq exposes the mocked object through the .Object
property. So in your case, you could do:
parseVendorSupplytest.Object.FromCsv(csvLineTest);
That said. I'm not sure this is what you wanted to do in first place. Assuming you're trying to test ParseVendorSupply
using a mocked logger, I believe your code should look like:
[Test]
public void FromCsv_ParseCorrectly_Extradata()
{
var logger = new Mock<ILogger>();
var parseVendorSupply = new ParseVendorSupply(logger.Object);
string csvLineTest = "5,8,3,9,5";
var result = parseVendorSupplytest.FromCsv(csvLineTest);
// Add your assertions here
}
Also note that you can use the Mock.Of<T>()
shortcut to directly retrieve the mocked object if you don't need any setup:
var parseVendorSupply = new ParseVendorSupply(Mock.Of<ILogger>());
hmm, for some reason, before the logger and the mock framework, it was running with unit test pass, now receive Message: Expected: <System.ArgumentException> But was: no exception thrown", however when I debug exception was thrown
– JoeThomas
Nov 12 at 8:08
@JoeThomas You'll have to show a bit of code to explain :p The exception is caught in yourParseVendorSupply.FromCsv
method, so what does your assertion look like?
– Kevin Gosse
Nov 12 at 8:11
add a comment |
Moq exposes the mocked object through the .Object
property. So in your case, you could do:
parseVendorSupplytest.Object.FromCsv(csvLineTest);
That said. I'm not sure this is what you wanted to do in first place. Assuming you're trying to test ParseVendorSupply
using a mocked logger, I believe your code should look like:
[Test]
public void FromCsv_ParseCorrectly_Extradata()
{
var logger = new Mock<ILogger>();
var parseVendorSupply = new ParseVendorSupply(logger.Object);
string csvLineTest = "5,8,3,9,5";
var result = parseVendorSupplytest.FromCsv(csvLineTest);
// Add your assertions here
}
Also note that you can use the Mock.Of<T>()
shortcut to directly retrieve the mocked object if you don't need any setup:
var parseVendorSupply = new ParseVendorSupply(Mock.Of<ILogger>());
Moq exposes the mocked object through the .Object
property. So in your case, you could do:
parseVendorSupplytest.Object.FromCsv(csvLineTest);
That said. I'm not sure this is what you wanted to do in first place. Assuming you're trying to test ParseVendorSupply
using a mocked logger, I believe your code should look like:
[Test]
public void FromCsv_ParseCorrectly_Extradata()
{
var logger = new Mock<ILogger>();
var parseVendorSupply = new ParseVendorSupply(logger.Object);
string csvLineTest = "5,8,3,9,5";
var result = parseVendorSupplytest.FromCsv(csvLineTest);
// Add your assertions here
}
Also note that you can use the Mock.Of<T>()
shortcut to directly retrieve the mocked object if you don't need any setup:
var parseVendorSupply = new ParseVendorSupply(Mock.Of<ILogger>());
answered Nov 12 at 8:01
Kevin Gosse
32.5k35271
32.5k35271
hmm, for some reason, before the logger and the mock framework, it was running with unit test pass, now receive Message: Expected: <System.ArgumentException> But was: no exception thrown", however when I debug exception was thrown
– JoeThomas
Nov 12 at 8:08
@JoeThomas You'll have to show a bit of code to explain :p The exception is caught in yourParseVendorSupply.FromCsv
method, so what does your assertion look like?
– Kevin Gosse
Nov 12 at 8:11
add a comment |
hmm, for some reason, before the logger and the mock framework, it was running with unit test pass, now receive Message: Expected: <System.ArgumentException> But was: no exception thrown", however when I debug exception was thrown
– JoeThomas
Nov 12 at 8:08
@JoeThomas You'll have to show a bit of code to explain :p The exception is caught in yourParseVendorSupply.FromCsv
method, so what does your assertion look like?
– Kevin Gosse
Nov 12 at 8:11
hmm, for some reason, before the logger and the mock framework, it was running with unit test pass, now receive Message: Expected: <System.ArgumentException> But was: no exception thrown", however when I debug exception was thrown
– JoeThomas
Nov 12 at 8:08
hmm, for some reason, before the logger and the mock framework, it was running with unit test pass, now receive Message: Expected: <System.ArgumentException> But was: no exception thrown", however when I debug exception was thrown
– JoeThomas
Nov 12 at 8:08
@JoeThomas You'll have to show a bit of code to explain :p The exception is caught in your
ParseVendorSupply.FromCsv
method, so what does your assertion look like?– Kevin Gosse
Nov 12 at 8:11
@JoeThomas You'll have to show a bit of code to explain :p The exception is caught in your
ParseVendorSupply.FromCsv
method, so what does your assertion look like?– Kevin Gosse
Nov 12 at 8:11
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53257882%2fmoq-a-class-and-still-use-its-methods%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown